批改状态:未批改
老师批语:
预处理实现更新:
<?php
/**
* 预处理实现更新操作
*/
//1.连接数据库
require 'mysqli_connect.php';
//2.准备sql语句的模板
$sql = "UPDATE staff SET salary=? WHERE staff_id=?;";
//3.创建stmt对象(预处理对象):将SQL语句转为对象
$stmt = mysqli_stmt_init($db);
//4.用stmt对象检测当前的预处理语句是否正确
if(mysqli_stmt_prepare($stmt, $sql)) {
//将变量与语句中的占位符进行绑定,s:字符串,i:整数,d:小数
mysqli_stmt_bind_param($stmt, 'ii',$salary,$staff_id);
$salary = 9900; $staff_id = 3;
//执行SQL
if (mysqli_stmt_execute($stmt)) {
//受影响的记录数
if (mysqli_stmt_affected_rows($stmt) >0) {
echo '更新成功,主键是:'.$staff_id;
} else {
echo '没有更新记录';
}
} else {
exit(mysqli_stmt_errno($stmt).':'.mysqli_stmt_error($stmt));
}
} else {
exit(mysqli_stmt_errno($stmt).':'.mysqli_stmt_error($stmt));
}
//5.注销stmt对象
mysqli_stmt_close($stmt);
//6.关闭连接
mysqli_close($db);点击 "运行实例" 按钮查看在线实例
预处理实现删除:
<?php
/**
* 预处理实现删除操作
*/
//1.连接数据库
require 'mysqli_connect.php';
//2.准备sql语句的模板
$sql = "DELETE FROM staff WHERE staff_id=?;";
//3.创建stmt对象(预处理对象):将SQL语句转为对象
$stmt = mysqli_stmt_init($db);
//4.用stmt对象检测当前的预处理语句是否正确
if(mysqli_stmt_prepare($stmt, $sql)) {
//将变量与语句中的占位符进行绑定,s:字符串,i:整数,d:小数
mysqli_stmt_bind_param($stmt, 'i',$staff_id);
$staff_id = 34;
//执行SQL
if (mysqli_stmt_execute($stmt)) {
//受影响的记录数
if (mysqli_stmt_affected_rows($stmt) >0) {
echo '删除成功,主键是:'.$staff_id;
} else {
echo '没有删除记录';
}
} else {
exit(mysqli_stmt_errno($stmt).':'.mysqli_stmt_error($stmt));
}
} else {
exit(mysqli_stmt_errno($stmt).':'.mysqli_stmt_error($stmt));
}
//5.注销stmt对象
mysqli_stmt_close($stmt);
//6.关闭连接
mysqli_close($db);点击 "运行实例" 按钮查看在线实例
总结:
基本步骤:
1.连接数据库
2.准备sql语句的模板
3.创建stmt对象
4.用stmt对象检测当前的预处理语句是否正确
5.注销stmt对象
6.关闭连接
预处理就是先设定标识符,使用时再进行替代,更安全
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号