Correction status:Uncorrected
Teacher's comments:
效果图:
代码:
<?php //1.连接数据库 require 'connect.php'; //2.准备SQL语句 $sql = "UPDATE staff SET name=? WHERE id=? ;"; //3.创建STMT预处理对象 $stmt = $mysqli->stmt_init(); //4.检测预处理SQL语句 if ($stmt->prepare($sql)) { //用二维数组来保存要更新的记录 $data[] = ['name'=> '张无忌','id'=>1]; $data[] = ['name'=> '赵敏','id'=>2]; $data[] = ['name'=> '周芷若','id'=>3]; //绑定参数到预处理SQL语句 $stmt->bind_param('si',$name,$id); foreach ($data as $staff) { //准备数据 $name = $staff['name']; $id = $staff['id']; //执行预处理语句 $stmt->execute(); //检测运行结果 if ($stmt->affected_rows > 0 ){ echo '<br>更新成功'.$stmt->affected_rows.'条记录,更新主键id是:'.$id; } else { echo '<br>没有更新记录'; } } //5.注销stmt对象 $stmt->close(); } else { exit($stmt->errno.':'.$stmt->error); } //6. 关闭数据库连接 $mysqli->close();
点击 "运行实例" 按钮查看在线实例
总结:
连接数据库:require‘connect.php’;
执行SQL语句:UPDATE SET WHERE;
创建STMT对象:$stmt = $mysqli->stmt_init();
检测预处理SQL语句:if( $stmt->prepare($stmt));
注销stmt对象: $stmt->close();
关闭数据库:$mysqli->close();