Home > Backend Development > PHP Tutorial > Parsing PDO::prepare in PHP (with code example)

Parsing PDO::prepare in PHP (with code example)

autoload
Release: 2023-04-09 21:48:02
Original
3007 people have browsed it

  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())
Copy after login
  • 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 = &#39;SELECT id, height, heights
    FROM people
    WHERE heights < :heights AND height = :height&#39;;
    
$sth = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$sth->execute(array(&#39;:heights&#39; => 150, &#39;:height&#39; => &#39;tall&#39;));
$tall = $sth->fetchAll();
$sth->execute(array(&#39;:heights&#39; => 175, &#39;:height&#39; => &#39;small&#39;));
$small = $sth->fetchAll();
?>
Copy after login

2 Use question marks Format preparation of SQL statement parameters

<?php
/* 传入数组的值,并执行准备好的语句 */
$sth = $dbh->prepare(&#39;SELECT id, height, heights
    FROM people
    WHERE heights < ? AND height = ?&#39;);
  
$sth->execute(array(150, &#39;tall&#39;));
$tall = $sth->fetchAll();
$sth->execute(array(175, &#39;small&#39;));
$small = $sth->fetchAll();
?>
Copy after login

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!

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