mysqli对prepare的支持对于大访问量的网站是颇有好处的,它极大地下降了系统开销,并且保证了建立查询的稳定性和安全性。prepare准备语句分为绑定参数和绑定结果,下面将会一一介绍! php
(1)绑定参数
看下面php代码:
html
<?php //建立链接 $mysqli=new mysqli("localhost","root","","volunteer"); //检查链接是否被建立 if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } /* * 建立一个准备查询语句: * ?是个通配符,能够用在任何有文字的数据 * 至关于一个模板,也就是预备sql语句 */ if ($stmt = $mysqli->prepare("insert into `vol_msg`(mid,content) values(?,?)")){ /*第一个参数是绑定类型,"s"是指一个字符串,也能够是"i",指的是int。也能够是"db", * d表明双精度以及浮点类型,而b表明blob类型,第二个参数是变量 */ $stmt->bind_param("is",$id,$content); //给变量赋值 $id = ""; $content = "这是插入的内容"; //执行准备语句 $stmt->execute(); //显示插入的语句 echo "Row inserted".$stmt->affected_rows; //下面还能够继续添加多条语句,不须要prepare预编译了 //关闭数据库的连接 $mysqli->close(); } ?>以上php实例运行结果:
(2).绑定结果:绑定结果就是将你绑定的字段给php变量,以便必要时使用这些变量
请看下面的php代码:
mysql
<?php //建立链接 $mysqli=new mysqli("localhost","root","","volunteer"); //设置mysqli编码 mysqli_query($mysqli,"SET NAMES utf8"); //检查链接是否被建立 if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } //建立准备语句 if ($stmt = $mysqli->prepare("select mid,content from `vol_msg`")){ //执行查询 $stmt->execute(); //为准备语句绑定实际变量 $stmt->bind_result($id,$content); //显示绑定结果的变量 while($stmt->fetch()){ echo "第".$id."条: ".$content."<br />"; } //关闭数据库的连接 $mysqli->close(); } ?>参考阅读:http://www.manongjc.com/article/1194.html