php中對MYSQL操作之預處理技術(2)數據庫dql查詢語句

<?php
//預處理技術

//創建一個mysqli對象
$mysqli = new MySQLi("主機名","mysql用戶名","密碼","數據庫名");

//判斷是否鏈接成功
if($mysqli->connect_error){
	die($mysqli->connect_error);
}

//創建預編譯對象
$sql = "select id,name,age,qq from 表名 where id<?";
$mysqli_compile = $mysqli->prepare($sql);

//綁定參數
$id=10;

//給?處進行賦值,"ssi"指string,string,int,數據類型和順序一一對應
//bind_param()這裏參數數目是可變。
$mysqli_compile->bind_param("i",$id);

//綁定結果集,這裏是用引用傳參的方式
$mysqli_compile->bind_result($name,$age,$qq);

//執行語句
$res = $mysqli_compile->execute();

//失敗打印出原因
if(!$res){
	die("失敗原因=".$mysqli_compile-error);
}

//取出綁定結果值
while($mysqli_compile->fetch()){
	echo "--$id--$name--$age--$qq";
}

//如果還要取其他的結果可以再次綁定參數取結果,但不用綁定結果集

//釋放結果集
$mysqli_compile->free_result();

//關閉資源,除去數據庫的預編譯的指令
$mysqli_compile->close();

//關閉鏈接資源
$mysqli->close();
?>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章