該方案防止sql注入php
注意:這裏只需創建一次鏈接,之後都是發數據便可!mysql
案例1:利用簡單預處理,往數據庫中執行dml語句插入(更新,刪除同種方法)信息:preparestatment.phpsql
<?php數據庫
//建立mysqli對象 ide
$mysqli=new mysqli("localhost","root","123456","test");fetch
//建立預編譯對象rest
$sql="insert into user (name,password,email,age) values(?,?,?,?)";對象
$mysqli_stmt=$mysqli->prepare($sql) or die($mysqli->error);blog
$mysqli->query("set names utf8");ip
//綁定參數
$name="張三";
$password="zs";
$email="zs@163.com";
$age=26;
//參數綁定->給?賦值,這裏類型和順序要一致!
$mysqli_stmt->bind_param("sssi",$name,$password,$email,$age);
$a=$mysqli_stmt->execute();
if(!$a){
die("操做失敗".$mysqli_stmt->execute());
}else {
echo " 操做ok ";
}
//釋放
$mysqli->close();
用命令增長的新記錄!成功!
若是繼續添加,就不須要再執行$mysqli->prepare()了!
如今是隻發數據,鏈接也沒斷開,這樣效率會很高!
<?php
//建立mysqli對象
$mysqli=new mysqli("localhost","root","123456","test");
//建立預編譯對象
$sql="insert into user (name,password,email,age) values(?,?,?,?)";
$mysqli_stmt=$mysqli->prepare($sql) or die($mysqli->error);
$mysqli->query("set names utf8");
//綁定參數
$name="張三";
$password="zs";
$email="zs@163.com";
$age=26;
//參數綁定->給?賦值,這裏類型和順序要一致!
$mysqli_stmt->bind_param("sssi",$name,$password,$email,$age);
$a=$mysqli_stmt->execute();//每個語句後面都要有一個執行語句!
//繼續添加
$name="李四";
$password="ls";
$email="ls@sohu.com";
$age="58";
$mysqli_stmt->bind_param("sssi",$name,$password,$email,$age);
$a=$mysqli_stmt->execute();
$name="王五";
$password="ww";
$email="ww@sohu.com";
$age="109";
$mysqli_stmt->bind_param("sssi",$name,$password,$email,$age);
$a=$mysqli_stmt->execute();
if(!$a){
die("操做失敗".$mysqli_stmt->execute());
}else {
echo " 操做ok ";
}
//釋放
$mysqli->close();
執行時,一次添加3條記錄!
案例2:用預處理執行dql語句,查詢id>10的用戶,如何預防sql注入
<?php
//建立mysqli對象
$mysqli=new mysqli("localhost","root","123456","test");
if(mysqli_connect_error()){
die (mysqli_connect_error());
}
//建立預編譯對象
$sql="select id,name,email from user where id>?";
$mysqli_stmt=$mysqli->prepare($sql) or die($mysqli->error);
$mysqli->query("set names utf8");
//綁定參數
$id=10;
//參數綁定->給?賦值,這裏類型和順序要一致!
$mysqli_stmt->bind_param("i",$id);
//綁定結果集
$mysqli_stmt->bind_result($id,$name,$email);
//執行
$mysqli_stmt->execute();
//取出綁定的值
while($mysqli_stmt->fetch()){
echo "<br/>--$id--$name--$email---";
}
//關閉資源
//釋放結果
$mysqli_stmt->free_result();
//關閉預編譯語句
$mysqli_stmt->close();
//關閉連接
$mysqli->close();
Id>10的都列出來了!
地址引用,因此結果能返回回來!
Sql注入的狀況:
還有一種方式,用limit命令也可致使!
不當心輸入的命令,就能夠獲取到更多的信息,這對開發者來講,是很是危險的漏洞!
案例3:
<?php
function showtable($table_name){
$mysqli=new mysqli("localhost","root","123456","test");
if (mysqli_connect_error()){
die (mysqli_connect_error());
}
$sql="select * from $table_name";
$res=$mysqli->query($sql);
echo "共有 行".$res->num_rows."--列=".$res->field_count;
$res->free();
$mysqli->close();
}
showtable("user");