mysqli扩展库---------预处理技术

1, PHP程序与mysql之间处理sql语句流程如下,减少执行时间方式有三种:

① 减少php发送sql次数;

② 减少php与mysql之间网络传输时间;

③ 减少mysql的编译时间;

2, 预编译可以减少数据库执行时间,同时可以防止sql注入攻击。预编译示例如下:

① 向user1中插入3条记录。

<?php
//预编译演示
//需求:请使用预处理的方式,向数据库添加三个用户

//1,创建mysqli对象
$mysqli = new MySQLi("10.252.158.217","root","521lhy","test");
if($mysqli->connect_error){
    die("连接错误".$mysqli->connect_error);
}
//2,创建预编译对象
$sql = "insert into user1 (name,password,email,age) VALUES (?,?,?,?)";
$mysqli_stmt = $mysqli->prepare($sql);

//绑定参数
$name ="小倩";
$password = "xiaoqian";
$email = "xiaoqian@126.com";
$age = 20;
//参数绑定->给》赋值,这里类型和顺序都要对应
$mysqli_stmt->bind_param("sssi",$name,$password,$email,$age);
//int对应i,double对应d,string对应s,boolean对应b
//执行
$b = $mysqli_stmt->execute();
if(!$b){
    echo $name."添加出错";
}

//继续添加
$name = "老妖";
$password = "laoyao";
$email = "laoyao@126.com";
$age = 120;
$mysqli_stmt->bind_param("sssi",$name,$password,$email,$age);
//执行
$b = $mysqli_stmt->execute();
if(!$b){
    echo $name."添加出错";
}

//继续添加
$name = "宁采臣";
$password = "ningcaichen";
$email = "ningcaichen@126.com";
$age = 24;
$mysqli_stmt->bind_param("sssi",$name,$password,$email,$age);
//执行
$b = $mysqli_stmt->execute();
if(!$b){
    echo $name."添加出错";
}

//释放
$mysqli->close();

② 查询所有id大于5的用户信息以及id大于10的用户信息。

<?php
//预编译演示
//需求:请使用预处理的方式,从数据库查询
//使用预处理的方法,查询所有id>5的用户的id,name,email
$mysqli = new MySQLi("10.252.158.217","root","521lhy","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->execute();

//绑定结果集
$mysqli_stmt->bind_result($id,$name,$email);

//取出绑定的值
while($mysqli_stmt->fetch()){
    echo "<br/>--$id--$name--$email";
}


echo "<br/>**********************************";
$id = 14;

//绑定参数
$mysqli_stmt->bind_param("i",$id);

//执行
$mysqli_stmt->execute();

//取出绑定的值
while($mysqli_stmt->fetch()){
    echo "<br/>--$id--$name--$email";
}

//关闭资源
//释放结果
$mysqli_stmt->free_result();
//关闭预编译
$mysqli_stmt->close();

//关闭连接
$mysqli->close();

3, 防止sql注入攻击方式,$sql = “select * from user where username = ‘aaa’ and password =’bbb’”;用此种方式查询时候,如果输入密码是xx’ or 1=’1,即$sql = “select * from user where username = ‘aaa’ and password =’ xx’ or 1=’1’”;这个也会成功的,这就是sql注入。

① 使用预编译。

② 改变验证数据库用户逻辑

$sql = “select password from user where username = ‘aaa’”;

//看看有没有查询到记录,如果有说明用户存在

If(从数据库查询的密码==用户输入的密码){

       //合法,用户合法

       header(“admin.php”);

}else{

       header(“err.php”);

}

 

posted on 2015-11-04 10:04  张三的哥哥  阅读(330)  评论(0编辑  收藏  举报