天天看點

php pdo學習筆記

pdo 資料庫抽象層,是對各種資料庫在使用上的一種抽象,使得php代碼不再依賴于特定的資料庫類型。

使用方法一:

首先生成對象:

try{
$pdo =new PDO("mysql:host=localhost;dbname=test;charset=utf8","root","335061");
}catch(PDOException $e){
    echo "錯誤".$e->getMessage();
}
           

構造方法中的三個參數第一個為資料庫連接配接時的環境配置,第二個為使用者名,第三個為密碼。

然後可以直接調用query方法執行查詢,傳回的是一個數組

$sql="select * from news";
$result=$pdo->query($sql);
$result=$result->fetchAll();
           

這是print_r($result) 的結果:

  Array( [0] => Array ( [id] => 10 [title] => 山上有個老和尚 [dates] => 2015-08-14 [contents] => 哎呀哎呀哎呀删了藥 ) [1] => Array ( [id] => 11 [title] => 人來瘋 [dates] => 2015-08-14 [contents] => 拳打南山養老院,腳踢北海幼稚園 ) [2] => Array ( [id] => 12 [title] => 安卓 [dates] => 2015-08-21 [contents] => 視訊播放 ))

這種查詢方法跟使用mysql_connect,mysql_query,mysql_fetch系列函數查詢沒太大差別。

pdo有另外一種查詢方法。

使用方法二(prepare方式):

跟前面差別主要在于查詢的那一步。

$sql=$pdo->prepare("select * from news where id= ? ");
$sql->bindParam(1,$id);
$id=11;
$row=$sql->execute();

//foreach($sql as $r){
//    print_r($r);
//}<pre name="code" class="php">while($result=$sql->fetch(PDO::FETCH_ASSOC)){
    foreach($result as $k=>$v){
        echo $k."   ".$v."<br>";
    }
}
           

結果:

id 11title 人來瘋dates 2015-08-14contents 拳打南山養老院,腳踢北海幼稚園

預處理語句中的?可以用别名方式代替,形如“select * from news whrere id= :id”;

$sql->binParam("id",$id);

在bind那一步,指明$sql中?的值,可以替換成$sql->bindValue(1,1,PDO::PARAM_INT)。

$sql中,?還可以換成:id。相應的$sql->bindParam("id",1,PDO::PARAM_INT)

綁定還可以在$sql->excute()中進行,形如$sql->excute(array(11));

在查詢前可以綁定參數,查詢後可以将結果綁定給變量。

$sql=$pdo->prepare("select * from news where id= ? ");
$sql->bindParam(1,$id);
$id=11;
$row=$sql->execute();
$sql->bindColumn(1,$id);
$sql->bindColumn(2,$title);
$sql->bindColumn(3,$date);
$sql->bindColumn(4,$contents);
while($result=$sql->fetch()){
    echo $id."  ".$title."  ".$date." ".$contents."<br>";
}
           

執行結果為

11 人來瘋 2015-08-14 拳打南山養老院,腳踢北海幼稚園

防止注入:

$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

由資料庫執行轉義,charset設定成與資料庫相同。