PDO::prepare — 准备要执行的SQL语句并返回一个 PDOStatement 对象(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)
- 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 。
- <?php
- /* 通过数组值向预处理语句传递值 */
- $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();
- ?>
- <?php
- /* 通过数组值向预处理语句传递值 */
- $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();
- ?>