pdo的預處理

pdo的預處理

PDOStatement類:準備語句,處理結果集
也就是預處理,安全,高效,推薦使用
兩種佔位符號:?參數 索引數組,按索引順序使用
名子參數 關聯數組,按名稱使用,和順序無關,以冒號開頭,自己定義
$stmt=$pdo->prepare($sql); $sql可是是任意sql語句,這與mysqli不同
兩種點位符號
try{
	$pdo=new PDO("mysql:host=localhost;dbname=mysqldb","root","snail");
}catch(PDOException $e){
	echo $e->getMessage();
}

//準備一條語句,並放到服務器端,而且編譯
$stmt=$pdo->prepare("insert into shop(name,price)values(?,?)");
// $stmt=$pdo->prepare("insert into shop(name,price)values(:na,:pr)");

//綁定參數(變量和參數綁定)
$stmt->bindparam(1,$name);
$stmt->bindparam(2,$price);
// $stmt->bindparam(":na",$name);
// $stmt->bindparam(":pr",$price);

$name="liwu11";
$price=234.4311;

if($stmt->execute()){
echo "執行成功";
echo "最後插入的ID:".$pdo->lastInsertId();
}else{
echo "執行失敗";
}
?>
//以數組方式向服務器傳值 
try{
$pdo=new PDO("mysql:host=localhost;dbname=mysqldb","root","snail");
}catch(PDOException $e){
echo $e->getMessage();
}

$stmt=$pdo->prepare("select * from shop where id >:id");

$stmt->execute(array(':id'=>130));

$row=$stmt->fetch();
print_r($row);

//用fetch(),fetchAll()來獲取查詢結果
try{
	$pdo=new PDO("mysql:host=localhost;dbname=mysqldb","root","snail");
}catch(PDOException $e){
	echo $e->getMessage();
}
$stmt=$pdo->prepare("select * from shop where id >:id");

$stmt->execute(array(':id'=>130));
/* 單條獲取fetch()

$stmt->setFetchMode(PDO::FETCH_ASSOC); //設置獲取模式
while($row=$stmt->fetch()){
	print_r($row);
}
*/

try{
$pdo=new PDO("mysql:host=localhost;dbname=mysqldb","root","snail");
}catch(PDOException $e){
echo $e->getMessage();
}
$stmt=$pdo->prepare("select * from shop where id >:id");

$stmt->execute(array(':id'=>130));
/* 單條獲取fetch()

$stmt->setFetchMode(PDO::FETCH_ASSOC); //設置獲取模式
while($row=$stmt->fetch()){
	print_r($row);
}
*/


//多條獲取fetchAll()
// $stmt->setFetchMode(PDO::FETCH_ASSOC);
$data=$stmt->fetchAll(PDO::FETCH_ASSOC); //也可以用上句進行設置
print_r($data);


//以表格輸出查詢結果

try{
$pdo=new PDO("mysql:host=localhost;dbname=mysqldb","root","snail");
}catch(PDOException $e){
echo $e->getMessage();
}

$stmt=$pdo->prepare("select id,name,price from shop where id >:id");

$stmt->execute(array(':id'=>130));

$stmt->bindColumn(id,$id);
$stmt->bindColumn(name,$name);
$stmt->bindColumn(price,$price);

for($i=0;$i<$stmt->columncount();$i++){
$field=$stmt->getColumnMeta($i);
}

while($stmt->fetch()){

}

echo "行:".stmt->rowcount()."";
echo "列:".stmt->columncount()."";
?>


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