Correction status:qualified
Teacher's comments:麻烦请到群文件中看一下对于作业的标题的要求
<?php $pdo = new PDO('mysql:dbname=php', 'root', 'root'); // 2. 准备SQL语句,创建预处理对象 $sql = 'INSERT INTO `staff` (`name`, `age`, `sex`, `position`, `mobile`, `hiredate`) '; $sql .= ' VALUES (:name, :age, :sex, :position, :mobile, :hiredate)'; //echo $sql;exit; $stmt=$pdo->prepare($sql); //预加载SQL语句 // 按之前做法, 应该先创建6个变量,然后逐一绑定到SQL语句占位符上 $stmt->bindParam('name', $name, PDO::PARAM_STR, 20); $stmt->bindParam('age', $age, PDO::PARAM_INT); $stmt->bindParam('sex', $sex, PDO::PARAM_INT); $stmt->bindParam('position', $position, PDO::PARAM_STR,20); $stmt->bindParam('mobile', $mobile, PDO::PARAM_STR, 11); $stmt->bindParam('hiredate', $hiredate, PDO::PARAM_INT); $stmt->execute(); $key = ['name', 'age', 'sex', 'position', 'mobile', 'hiredate']; $value = ['蔡成功', 42, 1, '大风厂长', '1358999321', time()]; $data = array_combine($key,$value); $stmt->execute($data); print_r($stmt); if($stmt ->rowCount()>0){ echo '成功插入一条数据'.$stmt->rowCount().'条记录'; }else{ echo'插入失败'; } $pdo=null; ?>
点击 "运行实例" 按钮查看在线实例
<?php $pdo= new PDO('mysql:dbname=php','root','root'); $sql1='select * from `staff` where `id`= 5'; $result = $pdo->prepare($sql1); $r=$result->execute(); if($result->rowCount()==0){ echo "没有此记录"; //exit; return; } $sql ='delete from `staff` where `id` = :id'; $stmt=$pdo->prepare($sql); if($stmt->execute(['id'=>5])){ //var_dump($stmt->rowCount());exit; if($stmt->rowCount()>0){ echo'您已删除一条数据'.$stmt->rowCount().'条记录'; }else{ echo '删除失败'; } }else{ echo print_r($stmt->errorInfo(),true); } ?>
点击 "运行实例" 按钮查看在线实例
<?php $pdo= new PDO('mysql:dbname=php','root','root');//连接数据库 $sql='UPDATE `staff` SET `position` = :position WHERE `id`=:id'; $stmt = $pdo->prepare($sql); $stmt->bindValue('position', '文化馆长', PDO::PARAM_STR); $stmt->bindValue('id', 16, PDO::PARAM_INT); $stmt->execute(); if($stmt->rowCount()>0){ echo '成功更改'.$stmt->rowCount().'条记录'; }else{ echo '更改失败'; } $pdo=null; ?>
点击 "运行实例" 按钮查看在线实例
<?php $pdo = new PDO('mysql:dbname=php', 'root', 'root'); // 2. 准备SQL语句,创建预处理对象 $stmt = $pdo->prepare('SELECT * FROM `staff` WHERE `age`>:age'); // 3. 执行SQL语句 $stmt->execute(['age'=>45]); // 4. 处理结果 // 查看记录数量 // echo '记录数量: ', $stmt->rowCount(); //判断结果集 如果结果集 执行遍历 if($stmt->rowCount()>0){ $stmt = $pdo->prepare('SELECT * FROM `staff` WHERE `age`>:age ORDER BY id ASC'); $stmt->execute(['age'=>45]); $xx=''; foreach($stmt->fetchAll(PDO::FETCH_ASSOC) as $row){ echo '<li>'.$row['id'].'---'.$row['name'].'---'.$row['sex'].'---'.$row['position'].'---'.$row['mobile'].'</li><br>'; } } ?>
点击 "运行实例" 按钮查看在线实例