PHP-Mysqli扩展库的预编译

2022-12-08,,,

(1)预编译的好处

假如要执行100条类似的sql语句,每一次执行,在MySQL端都会进行一次编译,效率很低。提高效率的方法就是--减少编译的次数。

先制造一个sql语句的模板,在MySQL端预先编译好,之后每次只需要传递数据即可。

除了提高效率之外,预编译还可以防止sql注入。

(2)dml语句的预编译

以向一个表中插入数据为例。表结构如下:

+----------+----------------------------+
| Field      | Type                           | 
+----------+----------------------------+
| id           | int(11)                       | 
| name      | varchar(20)                |
| height     | float(5,2)                   |
| gender    | enum('male','female')  | 
| class_id   | int(11)                      | 
+----------+----------------------------+

 // dml语句的预编译
// 1.连接数据库
$mysqli = new MySQLi('localhost','root','root','lianxi');
if(mysqli_connect_errno()){
echo '连接失败 '.$mysqli->connect_error;
}
$mysqli->query('set names utf8');
// 2.进行预编译
// 问号是占位符
$sql = 'insert into student values (?,?,?,?,?)';
// 通过MySQLi类的prepare()方法对sql模板进行编译,返回一个MySQLi_STMT类对象
$stmt = $mysqli->prepare($sql) or die($mysqli->connect_error);
// 利用MySQLi_STMT类中的bind_param()方法绑定参数。第一个参数表示各个字段的类型,i(int)、s(string)、d(double)
$stmt->bind_param('isdii',$id,$name,$height,$gender,$classId);
// 3.利用MySQLi_STMT类中的execute()方法插入数据
$id = null;
$name = 'Mildred';
$height = 165.00;
$gender = 2;
$classId = 12;
$stmt->execute() or die($stmt->error);
// 继续插入数据
$id = null;
$name = 'Shaw';
$height = 174.50;
$gender = 1;
$classId = 11;
$stmt->execute() or die($stmt->error); // 关闭连接
$stmt->close();
$mysqli->close();

(3)dql语句的预编译

和dml语句不同的地方在于,除了要绑定参数,还需要绑定结果集

 // dql语句的预编译
// 1.连接数据库
$mysqli = new MySQLi('localhost','root','root','lianxi');
if(mysqli_connect_error()){
die('连接失败 '.$mysqli->connect_error);
}
$mysqli->query('set names utf8');
// 2.编译sql语句
$sql = 'select * from student where id>?';
$stmt = $mysqli->prepare($sql) or die($mysqli->error);
// 3.绑定参数
$stmt->bind_param('i',$id);
// 4.绑定结果集
$stmt->bind_result($id,$name,$height,$gender,$classId);
// 5.执行
$id = 2;
$stmt->execute();
// 6.利用MySQLi_STMT类中的fetch()方法,通过循环得到查询的数据
while($stmt->fetch()){
echo $id.'--'.$name.'--'.$height.'--'.$gender.'--'.$classId;
echo '<br>';
}
// 7.关闭连接
$stmt->free_result();
$stmt->close();
$mysqli->close();

PHP-Mysqli扩展库的预编译的相关教程结束。

《PHP-Mysqli扩展库的预编译.doc》

下载本文的Word格式文档,以方便收藏与打印。