PDO
A database connection.
Syntax
new PDO(string $dsn, ?string $username = null, ?string $password = null, ?array $options = null)Parameters
| Parameter | Type | Description |
|---|---|---|
| $dsn | string | The connection string: the database type, the server address, the database name. |
| $username | ?string | Optional. The user name. |
| $password | ?string | Optional. The password. |
| $options | ?array | Optional. Connection settings. |
Return value
PDOAn object with the `query()`, `prepare()`, `exec()` and `beginTransaction()` methods.
Examples
Connecting, creating a table and querying:
<?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')");
echo $pdo->query('SELECT COUNT(*) FROM users')->fetchColumn();Output:
2A transaction:
<?php
$pdo = new PDO('sqlite::memory:');
$pdo->exec('CREATE TABLE accounts (id INTEGER PRIMARY KEY, balance INTEGER)');
$pdo->exec('INSERT INTO accounts (balance) VALUES (500), (100)');
$pdo->beginTransaction();
$pdo->exec('UPDATE accounts SET balance = balance - 200 WHERE id = 1');
$pdo->exec('UPDATE accounts SET balance = balance + 200 WHERE id = 2');
$pdo->commit();
echo implode(', ', $pdo->query('SELECT balance FROM accounts')->fetchAll(PDO::FETCH_COLUMN));Output:
300, 300Notes
A MySQL connection string looks like this: mysql:host=localhost;dbname=shop;charset=utf8mb4. Pass user data only through prepare(), never by inserting it into the query text.
See also
- PDOStatement — A prepared statement and its result.
- Exception — The base class of exceptions.
Related recipes
- How to check whether a row exists in a database
- How to connect to a database
- How to connect to MySQL with MySQLi
- 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
- Connecting to a database — Working with a database in PHP through PDO — connecting, creating a table, selecting rows and handling errors.