对预处理的理解:
想想看。假如我们要插入很多1000个用户.怎么做?for循环,还是mysqli处理多条sql, no,这些处理很慢的,php里面有很多操作mysql数据库的函数,无非是把sql语句传递给mysql数据库,真正处理sql语句的是mysql,mysql数据库是要编译sql语句迚行执行的,上面这两种操作会对相同的sql语句迚行多次编译,有这必要吗?程序员总是很聪明的,于是有了mysqli预处理技术mysqli还能防止sql注入.
预处理的意思是先提交sql语句到mysql服务端,执行预编译,客户端执行sql语句时,只需上传输入参数即可,这点和存储过程有点相似.摘抄网上滴.^_^
DML语句的预处理:
<?php
//连接数据库
$conn=new mysqli("localhost","root");
if($conn->connect_error) echo "数据库连接失败$conn->connect_error";
$conn->select_db("php");
//创建预编译对象,绑定参数
$sql="insert into score (name,score) values (?,?)";
$stmt=$conn->prepare($sql);
$stmt->bind_param("si",$name,$score);
//执行....
$name="mike";
$score=100;
$stmt->execute();
$name="jone";
$score=100;
$stmt->execute();
?
DQL语句的预处理
<?php
$conn=new mysqli("localhost","root");
if($conn->connect_error) echo "数据库连接失败$conn->connect_error";
$conn->select_db("php");
$sql="select * from score where id>?";//此处查询的数据要和下出绑定的结果匹配.
$stmt=$conn->prepare($sql);
$stmt->bind_param("i",$id);
$stmt->bind_result($id,$name,$score);
$id=2;
$stmt->execute();
if(!$stmt->execute()) die("操作失败");
while($stmt->fetch())
{
echo "<br/>$id-----$name----$score";
}
echo "<br/>********************";
$id=1;
$stmt->execute();
if(!$stmt->execute()) die("操作失败");
while($stmt->fetch())
{
echo "<br/>$id-----$name----$score";
}
$stmt->free_result();//释放结果
$stmt->close();//关闭预编译的指令.
$conn->close();//关闭连接
?>
对于预处理的多次执行语句,可以使用for等循环语句代替.DQL语句的预处理在DML语句的预处理的基础上增加了输出和释放.
我自己觉得,预处理就是给数据库一个模版,对数据库说,你就按照这样给我处理,等下我传个参数给你,你把它放在?的位置,进行处理.处理完,模版我就不用了,你就销毁吧.