批改状态:未批改
老师批语:
一、知识点
1,数据库预处理操作是php操作mysql一个重点课程,重新定义了安全可靠的操作流程,流程更清楚,实现更安全的操作。
2,与mysql函数普通操作还是有一定的区别。
3,具体流程
定义数据库连接串,数据库连接,定义sql局域,封装stmt对象,判断语句执行是否正常,执行语句,返回影响记录数,返回结果,注销stmt对象,关系mysql数据连接。
二、代码部分
插入数据
<?php
require 'config.php'; //导入数据库连接配置项目
//1定义数据库基础连接
$conn=mysqli_connect( db_hn,db_un,db_pw,db_nm) or die('数据库连接错误');
//2,封装成预处理对象
$stmt=mysqli_stmt_init($conn);
//3,定义sql语句
$sql="INSERT INTO `student` SET name =?";
//4,判断语句是否有错误
if (mysqli_stmt_prepare($stmt,$sql))
{
//6,参数绑定
$name='aaiai';
mysqli_stmt_bind_param($stmt,'s',$name);
//5,执行语句
mysqli_stmt_execute($stmt);
if (mysqli_stmt_affected_rows($stmt)>0)
{
echo "新增加数据成功,主键ID为:".mysqli_stmt_insert_id($stmt);
}
else{
die('没有数据被插入');
}
}
else{
die('查询错误'.mysqli_stmt_error($stmt));
}
//注销对象,关闭数据库连接
mysqli_stmt_close($stmt);
mysqli_close($conn);点击 "运行实例" 按钮查看在线实例
更新操作
<?php
require 'config.php'; //导入数据库连接配置项目
//1定义数据库基础连接
$conn=mysqli_connect( db_hn,db_un,db_pw,db_nm) or die('数据库连接错误');
//2,封装成预处理对象
$stmt=mysqli_stmt_init($conn);
//3,定义sql语句
$sql="update student set name=? where id =?";
//4,判断语句是否有错误
if (mysqli_stmt_prepare($stmt,$sql))
{
//6,参数绑定
$name='ataa';
$id='2';
mysqli_stmt_bind_param($stmt,'si',$name,$id);
//5,执行语句
mysqli_stmt_execute($stmt);
if (mysqli_stmt_affected_rows($stmt)>0)
{
echo "更新数据成功";
}
else{
die('没有数据被更新');
}
}
else{
die('查询错误'.mysqli_stmt_error($stmt));
}
//注销对象,关闭数据库连接
mysqli_stmt_close($stmt);
mysqli_close($conn);点击 "运行实例" 按钮查看在线实例
删除
<?php
require 'config.php';
$conn=mysqli_connect( db_hn,db_un,db_pw,db_nm) or die('数据库连接错误');
$sql='delete from student where id=?';
$stmt=mysqli_stmt_init($conn);
if (mysqli_stmt_prepare($stmt,$sql))
{
$id=21;
mysqli_stmt_bind_param($stmt,'i',$id);
mysqli_stmt_execute($stmt);
if (mysqli_stmt_affected_rows($stmt)>0)
{
die('删除成功,共删除:'.mysqli_stmt_affected_rows($stmt).'条');
}
else{
exit('没有任何记录被删除');
}
}
else{
exit('执行错误');
}点击 "运行实例" 按钮查看在线实例
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号