(PHP 5 >= 5.1.0, PHP 7, PHP 8, PHP 8,PECL pdo >= 0.1.0)
PDO::prepare — 準(zhǔn)備要執(zhí)行的語句,并返回語句對象
為 PDOStatement::execute() 方法準(zhǔn)備待執(zhí)行的 SQL 語句。 語句模板可以包含零個(gè)或多個(gè)參數(shù)占位標(biāo)記,格式是命名(:name)或問號(?)的形式,當(dāng)它執(zhí)行時(shí)將用真實(shí)數(shù)據(jù)取代。 在同一個(gè)語句模板里,命名形式和問號形式不能同時(shí)使用;只能選擇其中一種參數(shù)形式。 請用參數(shù)形式綁定用戶輸入的數(shù)據(jù),不要直接字符串拼接到查詢里。
調(diào)用 PDOStatement::execute() 時(shí),每一個(gè)值的參數(shù)占位標(biāo)記,名稱必須唯一。 除非啟用模擬(emulation)模式,同一個(gè)語句里無法使用重名的參數(shù)。
注意:
參數(shù)占位符僅能字面上展示完整的數(shù)據(jù)。不能是字面的一部分,不能是關(guān)鍵詞,不能是標(biāo)識符,不能是其他任意的范圍。 舉例說明:不能把多個(gè)值綁到單個(gè)參數(shù)里,然后在 SQL 語句里用 IN() 查詢。
如果用不同參數(shù),通過 PDO::prepare() 和 PDOStatement::execute() 多次調(diào)用同一個(gè) SQL 語句,將提升應(yīng)用的性能 —— 驅(qū)動(dòng)可以讓客戶端/服務(wù)器緩存查詢和元信息。 同時(shí),調(diào)用 PDO::prepare() 和 PDOStatement::execute() 還能阻止 SQL 注入攻擊,不需要給參數(shù)手動(dòng)加引號與轉(zhuǎn)義。
如果內(nèi)置驅(qū)動(dòng)不支持參數(shù),PDO 將模擬出參數(shù)的功能;如果驅(qū)動(dòng)僅僅支持其中一種風(fēng)格(命名參數(shù)和問號參數(shù)兩種),也會自動(dòng)重寫到另外一種風(fēng)格。
注意: The parser used for emulated prepared statements and for rewriting named or question mark style parameters supports the non standard backslash escapes for single- and double quotes. That means that terminating quotes immediately preceeded by a backslash are not recognized as such, which may result in wrong detection of parameters causing the prepared statement to fail when it is executed. A work-around is to not use emulated prepares for such SQL queries, and to avoid rewriting of parameters by using a parameter style which is natively supported by the driver.
statement
必須是對目標(biāo)數(shù)據(jù)庫服務(wù)器有效的 SQL 語句模板。
driver_options
數(shù)組包含一個(gè)或多個(gè) key=>value 鍵值對,為返回的 PDOStatement 對象設(shè)置屬性。
常見用法是:設(shè)置 PDO::ATTR_CURSOR
為 PDO::CURSOR_SCROLL
,將得到可滾動(dòng)的光標(biāo)。
某些驅(qū)動(dòng)有驅(qū)動(dòng)級的選項(xiàng),在 prepare 時(shí)就設(shè)置。
如果數(shù)據(jù)庫服務(wù)器完成準(zhǔn)備了語句,
PDO::prepare() 返回
PDOStatement 對象。
如果數(shù)據(jù)庫服務(wù)器無法準(zhǔn)備語句,
PDO::prepare() 返回 false
或拋出
PDOException (取決于 錯(cuò)誤處理器)。
注意:
模擬模式下的 prepare 語句不會和數(shù)據(jù)庫服務(wù)器交互,所以 PDO::prepare() 不會檢查語句。
示例 #1 命名參數(shù)形式的 SQL 語句模板
<?php
/* 傳入數(shù)組的值,并執(zhí)行準(zhǔn)備好的語句 */
$sql = 'SELECT name, colour, calories
FROM fruit
WHERE calories < :calories AND colour = :colour';
$sth = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$sth->execute(array(':calories' => 150, ':colour' => 'red'));
$red = $sth->fetchAll();
$sth->execute(array(':calories' => 175, ':colour' => 'yellow'));
$yellow = $sth->fetchAll();
?>
示例 #2 問號形式的 SQL 語句模板
<?php
/* 傳入數(shù)組的值,并執(zhí)行準(zhǔn)備好的語句 */
$sth = $dbh->prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < ? AND colour = ?');
$sth->execute(array(150, 'red'));
$red = $sth->fetchAll();
$sth->execute(array(175, 'yellow'));
$yellow = $sth->fetchAll();
?>