For faster navigation, this Iframe is preloading the Wikiwand page for PHP Data Objects.

PHP Data Objects

PDO(PHP Data Objects)是一種在PHP裡連接資料庫的使用介面[1]。PDO與mysqli[2]曾經被建議用來取代原本PHP在用的mysql[3]相關函數,基於資料庫使用的安全性,因為後者欠缺對於SQL資料隱碼的防護[4]

範例

[编辑]

以下是一個簡單的 PDO 更新交易資料庫的程式碼,其中採用了預處理的方式將執行語句與參數隔離:

<?php
    $query = "UPDATE `payment` SET `status` = '2', `id` = ?, `method` = ? WHERE `payment_id` = ? and `status` = '1'";
    $stmt = $this -> pdo -> prepare($query);
    $stmt -> bindParam(1, $id);
    $stmt -> bindParam(2, $type);
    $stmt -> bindParam(3, $payment_id);
    $result = $stmt -> execute();
?>


PDO默认会把数据库中查询的数据全部缓存下来,这在查询的结果集特别大时会有各种问题,比如消耗太多服务器资源,或造成运行的脚本因内存超限而终止。
下面的代码使用PDO对象的setAttribute方法来禁用缓存。

<?php
$dsn = "mysql:host=" . DATABASE_HOST . ";port=" . DATABASE_PORT . ";dbname=" . DATABASE_NAME;
$username = DATABASE_USERNAME;
$passwd = DATABASE_PASSWORD;
$pdoConn = new PDO($dsn, $username, $passwd);

$sql = "select * from big_table"; //假设这个表行数超多

$pdoConn->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false); //禁用缓存
$stmt = $pdoConn->query($sql);
$i = -1;
while ($row = $stmt->fetch()) {
    $i ++;
    if ($i % 10000) { //每一万个数据采样显示一下
        continue;
    }
    var_dump($i);
    var_dump($row);
}
?>

資料庫支援

[编辑]

参考文献

[编辑]
  1. ^ PHP: PDO - Manual. [2014-02-18]. (原始内容存档于2014-02-23). 
  2. ^ MySQL Improved Extension. [2014-02-18]. (原始内容存档于2014-02-23). 
  3. ^ Original MySQL API. [2014-02-18]. (原始内容存档于2014-02-23). 
  4. ^ PHP-DEV deprecating ext/mysql' - MARC. [2014-02-18]. (原始内容存档于2014-10-14). 

外部連結

[编辑]
{{bottomLinkPreText}} {{bottomLinkText}}
PHP Data Objects
Listen to this article

This browser is not supported by Wikiwand :(
Wikiwand requires a browser with modern capabilities in order to provide you with the best reading experience.
Please download and use one of the following browsers:

This article was just edited, click to reload
This article has been deleted on Wikipedia (Why?)

Back to homepage

Please click Add in the dialog above
Please click Allow in the top-left corner,
then click Install Now in the dialog
Please click Open in the download dialog,
then click Install
Please click the "Downloads" icon in the Safari toolbar, open the first download in the list,
then click Install
{{::$root.activation.text}}

Install Wikiwand

Install on Chrome Install on Firefox
Don't forget to rate us

Tell your friends about Wikiwand!

Gmail Facebook Twitter Link

Enjoying Wikiwand?

Tell your friends and spread the love:
Share on Gmail Share on Facebook Share on Twitter Share on Buffer

Our magic isn't perfect

You can help our automatic cover photo selection by reporting an unsuitable photo.

This photo is visually disturbing This photo is not a good choice

Thank you for helping!


Your input will affect cover photo selection, along with input from other users.

X

Get ready for Wikiwand 2.0 🎉! the new version arrives on September 1st! Don't want to wait?