Blogger Information
Blog 33
fans 0
comment 0
visits 24652
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
MySQLi面向过程:使用预处理技术实现更新与删除操作--2018.04.30上传
张鑫的博客
Original
918 people have browsed it

总结:

常用函数:

$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);

运行实例 »

点击 "运行实例" 按钮查看在线实例



Correction status:qualified

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post