批改状态:合格
老师批语:
以下是用php面向过程使用预处理对数据库中的数据进行更新:
<?php
/*
* 预处理对象: stmt Statement对象
* stmt对应着一个SQL语句的模板(变量分离 用占位符进行替换)
*/
//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=9999; $staff_id= 4;
//执行sql
if (mysqli_stmt_execute($stmt)){
//受影响的记录数
if (mysqli_stmt_affected_rows($stmt)>0){
echo 'Update success!';
}else{
echo 'No row updated!';
}
}else{
exit(mysqli_stmt_errno($stmt).' : '.mysqli_stmt_error($stmt));
}
}else{
exit(mysqli_stmt_errno($stmt).' : '.mysqli_stmt_error($stmt));
}
//注销stmt对象
mysqli_stmt_close($stmt);
//关闭数据库
mysqli_close($db);MySQL里面的数据如下:

staff_id是4的 salary是4445
现在运行上面的php代码:

MySQL的表格更新为:

可见satff_id为4的salary已经被更新为9999.
以下是用php面向过程使用预处理对数据库中的数据进行删除操作:
<?php
/*
* 预处理对象: stmt Statement对象
* stmt对应着一个SQL语句的模板(变量分离 用占位符进行替换)
*/
//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 = 24;
//执行sql
if (mysqli_stmt_execute($stmt)){
//受影响的记录数
if (mysqli_stmt_affected_rows($stmt)>0){
echo 'DELETE success!';
}else{
echo 'No row was deleted!';
}
}else{
exit(mysqli_stmt_errno($stmt).' : '.mysqli_stmt_error($stmt));
}
}else{
exit(mysqli_stmt_errno($stmt).' : '.mysqli_stmt_error($stmt));
}
//注销stmt对象
mysqli_stmt_close($stmt);
//关闭数据库
mysqli_close($db);MySQL数据库里面的data在php运行之前:

运行之后:


可见staff_id为24的那一项已经被删除了。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号