Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

PDO

A database connection.

Syntax

new PDO(string $dsn, ?string $username = null, ?string $password = null, ?array $options = null)

Parameters

ParameterTypeDescription
$dsnstringThe connection string: the database type, the server address, the database name.
$username?stringOptional. The user name.
$password?stringOptional. The password.
$options?arrayOptional. 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:

2

A 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, 300

Notes

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

Related recipes

In the tutorial

  • Connecting to a database — Working with a database in PHP through PDO — connecting, creating a table, selecting rows and handling errors.

Thanks for reading!

Donate to the site — we work hard for you.