Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

PDOStatement

A prepared statement and its result.

Syntax

$statement = $pdo->prepare(string $query)

Parameters

ParameterTypeDescription
$querystringThe query text with `?` marks or `:name` placeholders in place of values.

Return value

PDOStatementAn object with the `execute()`, `fetch()`, `fetchAll()`, `fetchColumn()` and `rowCount()` methods.

Examples

A query with a parameter:

<?php
 
$pdo = new PDO('sqlite::memory:');
$pdo->exec('CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)');
$pdo->exec("INSERT INTO users (name, age) VALUES ('Anna', 25), ('Oleg', 31)");
 
$statement = $pdo->prepare('SELECT name FROM users WHERE age > ?');
$statement->execute([30]);
 
echo $statement->fetchColumn();

Output:

Oleg

Every row as an associative array:

<?php
 
$pdo = new PDO('sqlite::memory:');
$pdo->exec('CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)');
$pdo->exec("INSERT INTO users (name) VALUES ('Anna'), ('Oleg')");
 
$statement = $pdo->prepare('SELECT id, name FROM users ORDER BY id');
$statement->execute();
 
echo json_encode($statement->fetchAll(PDO::FETCH_ASSOC));

Output:

[{"id":1,"name":"Anna"},{"id":2,"name":"Oleg"}]

Notes

fetch() returns one row, or false when the rows run out; fetchAll() returns all the rows at once.

See also

  • PDO — A database connection.

Related recipes

In the tutorial

  • Prepared statements — PDO prepared statements in PHP — putting data into SQL safely and preventing SQL injection.

Thanks for reading!

Donate to the site — we work hard for you.