预处理的更操作
<?php //1.连接数据库 require 'mysqli_connect.php'; //2.准备SQL语句 $sql = "UPDATE staff SET name = ?,salary = ? WHERE staff_id = ?;"; //3.创建STMT预处理对象 $stmt = $mysqli->stmt_init(); //4.检测预处理SQL语句 if ($stmt->prepare($sql)) { //用二维数组来保存要添加的记录 $data[] = ['name'=> '王重阳','salary'=>9000,'staff_id'=>24]; //绑定参数到预处理SQL语句 $stmt->bind_param('sii',$name,$salary,$staff_id); foreach ($data as $staff) { //准备要更新的数据 $name = $staff['name']; $salary = $staff['salary']; $staff_id = $staff['staff_id']; //执行预处理语句 $stmt->execute(); //检测运行结果 if ($stmt->affected_rows > 0 ){ echo '<br>成功更新'.$stmt->affected_rows.'条记录'; } else { echo '<br>没有记录被更新'; } } //5.注销stmt对象 $stmt->close(); } else { //返回错误信息 exit($stmt->errno.':'.$stmt->error); } //6. 关闭数据库连接 $mysqli->close();
运行实例 »
PDO实现删除操作
<?php /医院 * 预处理删除数据 */ //1.连接数据库,创建pdo对象 try { $pdo = new PDO('mysql:dbname=php','root','root'); } catch (PDOException $e) { exit($e->getMessage()); } //2.准备sql语句 // DELETE FROM user WHERE user_id = 12 $sql = "DELETE FROM user WHERE user_id=:user_id"; //3.创建预处理对象stmt对象 if($stmt = $pdo->prepare($sql)) { //4.将参数绑定到stmt对象并执行 //准备参数 $param = ['user_id'=>12]; //绑定参数到SQL语句对象并执行 if ($stmt -> execute($param)){ //rowCount()返回更新的数量,如果大于0表示有记录被删除 if ($stmt->rowCount()>0) { echo '成功删除了'.$stmt->rowCount().'条记录'; } else { //等于0表示没有记录被删除 echo '没有记录被删除'; } } else { //执行失败的信息 print_r($stmt->errorInfo()); exit(); } } else { //$stmt语句对象创建失败 print_r($pdo->errorInfo()); exit(); }
运行实例 »
点击 "运行实例" 按钮查看在线实例