Correction status:qualified
Teacher's comments:
PDO 数据库新增记录
1准备数据库,用命名占位符:占位
2创建预处理对象
3绑定参数
4bindParam:绑定一个参数到指定的变量名(类似于占位符)
<?php //创建实例对象,连接数据库 $pdo = new PDO('mysql:dbhost=127.0.0.1;dbname=php','root','root'); //准备数据库,用命名占位符:占位 $sql = "INSERT `user` SET `name`=:name ,`email`=:email ,`password`=sha1(:password)"; //创建预处理对象 $stmt = $pdo->prepare($sql); //绑定参数 $data = ['name'=>'1111','email'=>'yang@php.cn','password'=>'123']; //bindParam:绑定一个参数到指定的变量名(类似于占位符) $stmt->bindParam(':name',$data['name'],PDO::PARAM_STR); $stmt->bindParam(':email',$data['email'],PDO::PARAM_STR); $stmt->bindParam(':password',$data['password'],PDO::PARAM_STR); if ($stmt->execute()) { // rowCount(): 返回受影响的记录行数 echo '<h3>成功添加了'.$stmt->rowCount().'条记录</h3>'; } else { echo '<h3>添加失败</h3>'; print_r($stmt->errorInfo()); exit(); } $stmt = null; // 关闭连接 $pdo = null; ?>
点击 "运行实例" 按钮查看在线实例
PDO 数据库删除记录
<?php //连接数据库 $pdo = new PDO('mysql:host=127.0.0.1;dbname=php','root','root'); //准备SQL语句,占位符我们不再用?,用"命名占位符" $sql = "DELETE FROM `user` WHERE `id`= :id"; //创建预处理对象 $stmt = $pdo->prepare($sql); if ($stmt->execute(['id'=>11]))//执行一条预处理语句 { // rowCount(): 返回受影响的记录数量 echo '<h3>成功删除了'.$stmt->rowCount().'条记录</h3>'; } else { echo '<h3>删除失败</h3>'; print_r($stmt->errorInfo()); exit(); } $stmt = null; // 关闭连接 $pdo = null;
点击 "运行实例" 按钮查看在线实例
PDO 数据库更新记录
<?php //连接数据库 $pdo = new PDO('mysql:host=127.0.0.1;dbname=php','root','root'); //准备SQL语句,占位符我们不再用?,用"命名占位符" $sql = "UPDATE `user` SET `email`= :email WHERE `id`= :id"; //创建预处理对象 $stmt = $pdo->prepare($sql); //执行一条预处理语句 $stmt->execute(['email'=>'yzf@qq.com','id'=>5]); echo '<h3>成功更新了'.$stmt->rowCount().'条记录</h3>'; $stmt = null; // 关闭连接 $pdo = null;
点击 "运行实例" 按钮查看在线实例
PDO 数据库查询记录
<?php //连接数据库 $pdo = new PDO('mysql:host=127.0.0.1;dbname=php','root','root'); //准备SQL语句,占位符我们不再用?,用"命名占位符" $sql = "SELECT `name`,`email` FROM `user` WHERE `id` <= :id";//后面跟条件 //创建预处理对象 $stmt = $pdo->prepare($sql); //执行一条预处理语句 $stmt->execute(['id'=>5]); while($row = $stmt->fetch(PDO::FETCH_ASSOC)) { echo var_export($row),'<br>'; }
点击 "运行实例" 按钮查看在线实例