PDO::prepare


PDO::prepare — 准备要执行的SQL语句并返回一个 PDOStatement 对象(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)

说明

语法

  1. public PDOStatement PDO::prepare ( string $statement [, array $driver_options = array() ] )

为 PDOStatement::execute() 方法准备要执行的SQL语句,SQL语句可以包含零个或多个命名(:name)或问号(?)参数标记,参数在SQL执行时会被替换。

你不能在 SQL 语句中同时包含命名(:name)或问号(?)参数标记,只能选择其中一种风格。

预处理 SQL 语句中的参数在使用PDOStatement::execute()方法时会传递真实的参数。

参数

statement
合法的SQL语句。

driver_options
此数组包含一个或多个 key=>value 对来设置 PDOStatement 对象的属性, 最常使用到是将PDO::ATTR_CURSOR值设置为PDO::CURSOR_SCROLL来请求一个可滚动游标。

返回值

如果成功,PDO::prepare()返回PDOStatement对象,如果失败返回 FALSE 或抛出异常 PDOException 。

实例

使用命名(:name)参数来准备SQL语句

  1. <?php
  2. /* 通过数组值向预处理语句传递值 */
  3. $sql = 'SELECT name, colour, calories
  4. FROM fruit
  5. WHERE calories < :calories AND colour = :colour';
  6. $sth = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
  7. $sth->execute(array(':calories' => 150, ':colour' => 'red'));
  8. $red = $sth->fetchAll();
  9. $sth->execute(array(':calories' => 175, ':colour' => 'yellow'));
  10. $yellow = $sth->fetchAll();
  11. ?>

使用问号(?)参数来准备SQL语句

  1. <?php
  2. /* 通过数组值向预处理语句传递值 */
  3. $sth = $dbh->prepare('SELECT name, colour, calories
  4. FROM fruit
  5. WHERE calories < ? AND colour = ?');
  6. $sth->execute(array(150, 'red'));
  7. $red = $sth->fetchAll();
  8. $sth->execute(array(175, 'yellow'));
  9. $yellow = $sth->fetchAll();
  10. ?>