PDOStatement
A prepared statement and its result.
Syntax
$statement = $pdo->prepare(string $query)Parameters
| Parameter | Type | Description |
|---|---|---|
| $query | string | The 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:
OlegEvery 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
- How to check whether a row exists in a database
- How to connect to a database
- How to count the rows in a table
- How to delete a row from a database
- How to get the id of an inserted row
- How to insert a row into a database
- How to paginate database results
- How to run several queries in a transaction
- How to search records by part of a string
- How to select rows from a database
- How to update a row in a database
In the tutorial
- Prepared statements — PDO prepared statements in PHP — putting data into SQL safely and preventing SQL injection.