23.5.4 预准备语句
使用预准备语句可提高重复使用语句的性能,在PHP中,使用prepare()方法来进行预准备语句查询,使用execute()方法来执行预准备语句。PHP有两种预准备语句:一种是绑定结果,另一种是绑定参数。
1.绑定结果
所谓绑定结果就是把PHP脚本中的自定义变量绑定到结果集中的相应字段上,这些变量就代表着所查询的记录,绑定结果的示例代码如下:
代码23-30 光盘\codes\第23章\23.5\bandResult.php<?php
$mysqli=newmysqli("localhost","root","root","sunyang");
//实例化mysqli
$query="select * from employee";
$result=$mysqli->prepare($query);
//进行预准备语句查询
$result->execute();
//执行预准备语句
$result->bind_result($id,$number,$name,$age);
//绑定结果
while($result->fetch()) {
echo$id;
echo$number;
echo$name;
echo$age;
}
$result->close();
//关闭预准备语句
$mysqli->close();
//关闭连接
?>
在绑定结果的时候,脚本中的变量要与结果集中的字段一一对应,绑定完以后,通过fetch()方法将绑定在结果集中的变量一一取出来,***将预准备语句和数据库连接分别关闭。
2.绑定参数
所谓绑定参数就是把PHP脚本中的自定义变量绑定到SQL语句中的参数(参数使用 "?"代替)上,绑定参数使用bind_param()方法,该方法的语法格式如下:bool bind_param ( string$types, mixed &$var1[, mixed &$... ] )
在上述语法中涉及到的参数说明如下。
types:绑定的变量的数据类型,它接受的字符种类包括4个,如表23-1所示。
表23-1 字符描述
字符种类
代表的数据类型
I
integer
D
double
S
string
B
blob
参数types接受的字符的种类和绑定的变量需要一一对应。
var1:绑定的变量,其数量必须要与SQL语句中的参数数量保持一致。
绑定参数的示例代码如下:
代码23-31 光盘\codes\第23章\23.5\bandParam.php<?php
$mysqli=newmysqli("localhost","root","root","sunyang");
//实例化mysqli
$query="insert into employee (emp_number,emp_name,emp_age)
values (?,?,?)";
$result=$mysqli->prepare($query);
$result->bind_param("ssi",$number,$name,$age);
//绑定参数
$number='sy0807';
$name='employee7';
$age=20;
$result->execute();
//执行预准备语句
$result->close();
$mysqli->close();
?>
在一个脚本中还可以同时绑定参数和绑定结果,示例代码如下:
代码23-32 光盘\codes\第23章\23.5\bandParamResult.php<?php
$mysqli=newmysqli("localhost","root","root","sunyang");
//实例化mysqli
$query="select * from employee where emp_id
$result=$mysqli->prepare($query);
$result->bind_param("i",$emp_id);
//绑定参数
$emp_id=4;
$result->execute();
$result->bind_result($id,$number,$name,$age);
//绑定结果
while($result->fetch()) {
echo$id."
";
echo$number."
";
echo$name."
";
echo$age."
";
}
$result->close();
$mysqli->close();
?>
【责任编辑:董书 TEL:(010)68476606】
点赞 0