Correction status:qualified
Teacher's comments:
<?php //连接数据库 $pdo = new PDO('mysql:host=127.0.0.1;dbname=php','root','root'); //执行操作 //插入语句模板 $sql = 'INSERT INTO `staff` (`name`,`age`,`sex`,`position`,`mobile`,`hiredate`) VALUES (:name, :age, :sex, :position, :mobile, :hiredate)'; $stmt = $pdo->prepare($sql); //绑定参数 //1.数据赋值方式添加 //$name = '孙连城'; //$age = 48; //$sex = 1; //$position = '光明区长'; //$mobile = '13501020101'; //$hiredate = time(); // //$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,30); //$stmt->bindParam(':mobile',$mobile,PDO::PARAM_STR,11); //$stmt->bindParam(':hiredate',$hiredate,PDO::PARAM_INT); // //$stmt->execute(); //die($stmt->debugDumpParams()); //2. 用数组 的方式简化参数绑定操作 //创建二个数组分别保存参数的键和值 $key = ['name', 'age', 'sex', 'position', 'mobile', 'hiredate']; $value = ['蔡成功', 42, 1, '大风厂长', '13401020304', time()]; //用array_combine()这个函数将键数组 与 值数组 合并成一个新的二维数组 $data = array_combine($key, $value); $stmt->execute($data); if($stmt->rowCount() > 0) { echo '成功添加了' . $stmt->rowCount() . '条记录'; } //关闭连接 $pdo = null;
点击 "运行实例" 按钮查看在线实例
<?php //更新数据 //1.连接数据库 $pdo = new PDO('mysql:host=127.0.0.1;dbname=php','root','root'); //2.执行sql操作 $sql = 'UPDATE `staff` SET `mobile` = :mobile WHERE `id` = :id'; $stmt = $pdo->prepare($sql); $stmt->execute(['mobile'=>'13301020303','id'=>7]); if ($stmt->rowCount() > 0) { echo '成功更新了' . $stmt->rowCount() . '条记录。'; } else { echo '更新失败,请检查'; } //3.关闭连接 $pdo = null;
点击 "运行实例" 按钮查看在线实例
<?php //删除数据 //1.连接数据库 $pdo = new PDO('mysql:host=127.0.0.1;dbname=php','root','root'); //2.执行sql操作 $sql = 'DELETE FROM `staff` WHERE `id`=:id'; $stmt = $pdo->prepare($sql); $stmt->execute(['id'=>9]); if ($stmt->rowCount() > 0) { echo '成功删除了' . $stmt->rowCount() . '条记录。'; } else { echo '删除失败,请检查'; } //3.关闭连接 $pdo = null;
点击 "运行实例" 按钮查看在线实例