天天看點

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()."";
?>