Home >Backend Development >PHP Tutorial >Parsing PDO::prepare in PHP (with code example)
PDO
is currently a more frequently used method to connect to the database. In order to improve operating efficiency, use prepared statements - prepare()
method , is a more effective path. This article will take you to take a look.
First you need to understand the syntax of PDO::prepare
public PDO::prepare ( string $statement , array $driver_options = array())
string $statement: must be a valid SQL statement template for the target database server .
$driver_options: The array contains one or more key=>value key-value pairs, which set properties for the returned PDOStatement
object.
Return value: If the database server completes preparing the statement, it returns the PDOStatement
object. If the database server cannot prepare the statement, it returns false
or throws PDOException
(depending on the error handler).
1. Prepare SQL statement parameters in the form of named parameters
<?php /* 传入数组的值,并执行准备好的语句 */ $sql = 'SELECT id, height, heights FROM people WHERE heights < :heights AND height = :height'; $sth = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY)); $sth->execute(array(':heights' => 150, ':height' => 'tall')); $tall = $sth->fetchAll(); $sth->execute(array(':heights' => 175, ':height' => 'small')); $small = $sth->fetchAll(); ?>
2 Use question marks Format preparation of SQL statement parameters
<?php /* 传入数组的值,并执行准备好的语句 */ $sth = $dbh->prepare('SELECT id, height, heights FROM people WHERE heights < ? AND height = ?'); $sth->execute(array(150, 'tall')); $tall = $sth->fetchAll(); $sth->execute(array(175, 'small')); $small = $sth->fetchAll(); ?>
Recommended: 《2021 PHP interview questions summary (collection)》《php video Tutorial》
The above is the detailed content of Parsing PDO::prepare in PHP (with code example). For more information, please follow other related articles on the PHP Chinese website!