批改状态:合格
老师批语:
总结:
常用函数:
$stmt=mysqli_stmt_init($db); //创建stmt对象
mysqli_stmt_prepare($stmt); //检测sql语句
mysqli_stmt_errno($stmt); //错误编号
mysqli_stmt_error($stmt); //错误信息
mysqli_stmt_bind_param($stmt,'sid',$s,$i,$d); //将变量与语句中的占位符进行绑定,S:字符串,i:整数,d:小数
mysqli_stmt_execute($stmt); //执行sql语句
mysqli_stmt_store_result($stmt); //获取结果集,查询语句才有结果集
mysqli_stmt_bind_result($stmt,$name,$salary); //将结果集的列与指定的变量进行绑定
mysqli_stmt_num_rows($stmt); //结果集中的记录数量
mysqli_stmt_fetch($stmt); //遍历结果集
mysqli_stmt_close($stmt); // 注销stmt对象
mysqli_close($db); // 关闭数据库连接
预处理技术实现更新操作代码:
<?php
// 1.连接数据库
require 'connect.php';
// 2.准备sql语句
// $sql = "DELETE FROM student WHERE id=?;";
$sql = "UPDATE student SET grade=?,course=? WHERE id=?;";
// 3.创建stmt对象
$stmt = mysqli_stmt_init($db);
// 4.检测sql语句
if (mysqli_stmt_prepare($stmt,$sql)) {
// 5.绑定参数
mysqli_stmt_bind_param($stmt,'isi',$grade,$course,$id);
$grade=95;
$course='css';
$id=2;
// 6.执行sql语句
mysqli_stmt_execute($stmt);
// 7.判断被影响的记录数
if (mysqli_stmt_affected_rows($stmt)>0) {
echo '成功更新了'.mysqli_stmt_affected_rows($stmt).'条记录';
}else{
echo '没有更新数据';
}
}else{
// 错误信息
echo mysqli_stmt_errno($stmt).':'.mysqli_stmt_error($stmt);
}
// 8.注销stmt对象
mysqli_stmt_close($stmt);
// 9.关闭数据库连接
mysqli_close($db);点击 "运行实例" 按钮查看在线实例
预处理技术实现删除操作代码:
<?php
// 1.连接数据库
require 'connect.php';
// 2.准备sql语句
$sql = "DELETE FROM student WHERE id=?;";
// $sql = "UPDATE student SET name=?,course=?,grade=? WHERE id=?;";
// 3.创建stmt对象
$stmt = mysqli_stmt_init($db);
// 4.检测sql语句
if (mysqli_stmt_prepare($stmt,$sql)) {
// 5.绑定参数
mysqli_stmt_bind_param($stmt,'i',$id);
$id=6;
// 6.执行sql语句
mysqli_stmt_execute($stmt);
// 7.判断被影响的记录数
if (mysqli_stmt_affected_rows($stmt)>0) {
echo '成功删除了'.mysqli_stmt_affected_rows($stmt).'条记录';
}else{
echo '没有删除数据';
}
}else{
// 错误信息
echo mysqli_stmt_errno($stmt).':'.mysqli_stmt_error($stmt);
}
// 8.注销stmt对象
mysqli_stmt_close($stmt);
// 9.关闭数据库连接
mysqli_close($db);点击 "运行实例" 按钮查看在线实例
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号