1、使用mysqli擴展庫 預處理技術 mysqli stmt 向數據庫添加3個用戶
復制代碼 代碼如下:
<?php
//mysqli擴展庫 預處理技術 mysqli stmt 向數據庫添加3個用戶
//1、創建mysqli對象
$mysqli = new MySQLi("localhost","root","root","test");
if($mysqli->connect_error){
die($mysqli->conncet_error);
}
//2、創建預編譯對象
$sql="insert into user1(name,password,email,age) values(?,?,?,?)";
$mysqli_stmt=$mysqli->prepare($sql);
//綁定參數
$name="小芳";
$password="123456";
$email="[email protected]";
$age=18;
//參數綁定->給?號賦值 這裡類型和順序要一致
$mysqli_stmt->bind_param("sssi",$name,$password,$email,$age);
//執行
$b=$mysqli_stmt->execute();
//繼續添加
$name="小楊";
$password="123456";
$email="[email protected]";
$age=18;
//參數綁定->給?號賦值 這裡類型和順序要一致
$mysqli_stmt->bind_param("sssi",$name,$password,$email,$age);
//執行
$b=$mysqli_stmt->execute();
//繼續添加
$name="小G";
$password="123456";
$email="[email protected]";
$age=18;
//參數綁定->給?號賦值 這裡類型和順序要一致
$mysqli_stmt->bind_param("sssi",$name,$password,$email,$age);
//執行
$b=$mysqli_stmt->execute();
if(!$b){
echo "操作失敗".$mysqli_stmt->error;
}else{
echo "操作成功";
}
//關閉預編譯
$mysqli_stmt->close();
$mysqli->close();
?>
2、使用預處理查詢id>5的用戶id name email
復制代碼 代碼如下:
<?php
//使用預處理查詢id>5的用戶id name email
$mysqli=new MySQLi("localhost","root","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 "<br/>$id--$name--$email";
}
//關閉資源
//釋放結果
$mysqli_stmt->free_result();
//關閉與編譯語句
$mysqli_stmt->close();
//關閉連接
$mysqli->close();
?>