PDO::prepare

PHP PDO 参考手册PHP PDO Reference Manual

PDO::prepare — Prepares an SQL statement for execution and returns a PDOStatement object (PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)


Description

Syntax

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

Prepares an SQL statement for execution by the PDOStatement::execute() method. The SQL statement can contain zero or more named (:name) or question mark (?) parameter markers. The parameters will be replaced when the statement is executed.

You cannot mix named (:name) and question mark (?) parameter markers in the same SQL statement; you must choose one style.

The parameters in a prepared SQL statement will be replaced with actual values when the PDOStatement::execute() method is called.


Parameters

statement
A valid SQL statement.

driver_options
This array contains one or more key=>value pairs to set attributes on the PDOStatement object. The most common use is to set the PDO::ATTR_CURSOR value to PDO::CURSOR_SCROLL to request a scrollable cursor.


Return Values

On success, PDO::prepare() returns a PDOStatement object. On failure, it returns FALSE or throws a PDOException.


Examples

Prepare an SQL statement using named (:name) parameters

Example

<?php /*Passing values to a prepared statement using an array*/ $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(); ?>

Prepare an SQL statement using question mark (?) parameters

Example

<?php /*Passing values to a prepared statement using an array*/ $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(); ?>

PHP PDO 参考手册PHP PDO Reference Manual

Other Extensions