php中使用mysql_stmt,预处理语句来处理select查询结果

许多PHP脚本通常都会执行除参数以外,其他部分完全相同的查询语句,针对这种重复执行一个查询,每次迭代使用不同的参数情况,MySQL 从4.1版本开始提供了一种名为预处理语句(prepared statement)的机制。它可以将整个命令向MySQL服务器发送一次,以后只有参数发生变化,MySQL服务器只需对命令的结构做一次分析就够了。 这不仅大大减少了需要传输的数据量,还提高了命令的处理效率。可以用mysqli扩展模式中提供的mysqli_stmt类的对象,去定义和执行参数化的 SQL命令。以下是使用这种机制实现的一个查询过程。

1 <?php

2

3 $db = new mysqli("localhost","user","password","testdb");

4

5 if (mysqli_connect_errno()){

6 printf("Error:%s\n",mysqli_connect_error());

7 exit;

8 }

9 else {

10 if ($stmt = $db->prepare("select id,name,author,price from book where name like ?")){

11

12 $stmt->bind_param('s',$n);

13 $n = "%p%";

14

15 $stmt->execute();

16

17 $stmt->store_result();

18 $stmt->bind_result($id,$name,$author,$price);

19 while ($stmt->fetch()){

20 printf("%s:%s,%s,%s<br/>",$id,$name,$author,$price);

21 }

22 $stmt->close();

23 }

24

25 $db->close();

26 }

27 ?>