Home > Database > Mysql Tutorial > mysqli预处理编译的深入理解_MySQL

mysqli预处理编译的深入理解_MySQL

WBOY
Release: 2016-06-01 13:23:36
Original
992 people have browsed it

bitsCN.com

记得以前php点点通也写过mysqli的预处理的php教程,那时候只是看书乱写的,没懂原理,数月过后,突然明白了很多:
想想看。假如我们要插入很多1000个用户,你怎么做,for循环?还是mysqli处理多条sql? no!这些处理很慢的,php里面有很多操作mysql数据库的函数,无非是把sql语句传递给mysql数据库,真正处理sql语句的是mysql,mysql数据库是要编译sql语句进行执行的,上面这两种操作会对相同的sql语句进行多次编译,有这必要吗?程序员总是很聪明的,于是有了mysqli预处理技术!mysqli还能防止sql注入攻击!
看看下面这个预编译代码:

//创建连接
$mysqli=new mysqli("localhost","root","","test");
//设置mysqli编码
mysqli_query($mysqli,"SET NAMES utf8");
//检查连接是否被创建
if (mysqli_connect_errno()) {
printf("Connect failed:".mysqli_connect_error());
exit();
}
//创建准备语句
$stmt = $mysqli->prepare("select id,username from `user` where `id` > ?");
/*************************************************************/
$id=5;
//绑定参数
$stmt->bind_param("i",$id);
//绑定结果集
$stmt->bind_result($id,$username);
//执行查询
$stmt->execute();
//显示绑定结果的变量
while($stmt->fetch()){
echo "第".$id."个用户: ".$username."
";
}
/**************************************************************/
/*www.phpddt.com为你提示:上面*之间的内容可以重复执行类似功能,不需要再次编译了*/
//释放结果
$stmt->free_result();
//关闭编译语句
$stmt->close();
//关闭数据库的链接
$mysqli->close();
?>

bitsCN.com
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template