Home > Backend Development > PHP Tutorial > Detailed explanation of mysql PDO::prepare usage

Detailed explanation of mysql PDO::prepare usage

巴扎黑
Release: 2023-03-07 21:38:01
Original
3618 people have browsed it

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() ] )
Copy after login

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 = &#39;SELECT name, colour, calories
    FROM fruit
    WHERE calories < :calories AND colour = :colour&#39;;
    $sth = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
    $sth->execute(array(&#39;:calories&#39; => 150, &#39;:colour&#39; => &#39;red&#39;));
    $red = $sth->fetchAll();
    $sth->execute(array(&#39;:calories&#39; => 175, &#39;:colour&#39; => &#39;yellow&#39;));
    $yellow = $sth->fetchAll();
    ?>
Copy after login

Use question mark (?) parameters to prepare SQL statements

<?php
/* 通过数组值向预处理语句传递值 */
$sth = $dbh->prepare(&#39;SELECT name, colour, calories
    FROM fruit
    WHERE calories < ? AND colour = ?&#39;);$sth->execute(array(150, &#39;red&#39;));
    $red = $sth->fetchAll();
    $sth->execute(array(175, &#39;yellow&#39;));
    $yellow = $sth->fetchAll();
    ?>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template