mysqli扩展库的预处理技术 mysqli stmt

//预编译演示
//1,创建mysqli对象
$mysqli=new mysqli("localhost","root","","test");
//2,创建预编译对象
$sql="insert into user1 (name,password,email,age) values(?,?,?,?)";
$mysqli_stmt=$mysqli->prepare($sql) or die($mysqli->error);
//绑定参数
$name="罐罐";
$password="guanguan";
$email="gg@qq.com";
$age="1";
//参数绑定->给?赋值
$mysqli_stmt->bind_param("sssi",$name,$password,$email,$age);
//执行
$b=$mysqli_stmt->execute();

if(!$b){
die("操作失败".$mysqli_stmt->error);
}else{
echo "操作成功";
}
$mysqli->close();



使用预处理的方式从数据库查询

//使用预处理方法,查询所有ID>5的数据
$mysqli=new mysqli("localhost","root","","test");
if(mysqli_connect_error()){
die(mysqli_connect_error());
}

//创建一个预定义对象?占位
$sql="select id,name,email from user1 where id>?";
$mysqli_stmt=$mysqli->prepare($sql);
$id=5;
//绑定参数
$mysqli_stmt->bind_param("i",$id);
//绑定结果集
$mysqli_stmt->bind_result($id,$name,$email);
//执行
$mysqli_stmt->execute();
//取出绑定的值
while($mysqli_stmt->fetch()){
echo "
--$id--$name--$email";
}
//关闭资源
//释放结果
$mysqli_stmt->free_result();
//关闭预编译语句
$mysqli_stmt->close();
//关闭连接
$mysqli->close();

预编译可以自动防止sql(结构化查询语句)注入攻击

posted @ 2015-10-08 19:10  岁月无心  阅读(202)  评论(0编辑  收藏  举报