PDO::prepare — Prepare the SQL statement to be executed and return 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() ] )
Prepare the SQL statement to be executed for the PDOStatement::execute() method. The SQL statement can contain zero or more named (:name) or question mark (?) parameters. Mark, parameters will be replaced when SQL is executed.
You cannot include both named (:name) or question mark (?) parameter markers in the SQL statement. You can only choose one of the styles.
The parameters in the preprocessed SQL statement will pass the real parameters when using the PDOStatement::execute() method.
Parameters
statement: Legal SQL statement.
driver_options: This array contains one or more key=>value pairs to set the properties of the PDOStatement object. The most commonly used is to set the PDO::ATTR_CURSOR value to PDO::CURSOR_SCROLL to request a scrollable cursor.
Return value
If successful, PDO::prepare() returns a PDOStatement object. If it fails, it returns FALSE or throws an exception PDOException.
Example
Use named (:name) parameters to prepare SQL statements
<?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(); ?>
Use question mark (?) parameters to prepare SQL statements
<?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(); ?>
The above is the detailed content of Detailed explanation of mysql PDO::prepare usage. For more information, please follow other related articles on the PHP Chinese website!