new PDO() Since: PHP 5(2004)
PDO is the standard interface for connecting to databases from PHP. It provides a unified API for working with multiple databases, including MySQL, PostgreSQL, and SQLite.
Syntax
// Connect to a database. $pdo = new PDO($dsn, $username, $password, $options); // Set a connection attribute. $pdo->setAttribute($attribute, $value); // Get a connection attribute. $pdo->getAttribute($attribute);
Method List
| Method | Description |
|---|---|
| new PDO($dsn, $user, $pass, $options) | Establishes a connection to the database. Throws a PDOException if the connection fails. |
| setAttribute($attribute, $value) | Sets an attribute on the PDO connection. You can configure error mode, fetch mode, character encoding, and more. |
| getAttribute($attribute) | Retrieves the current value of a connection attribute. Useful for checking the server version or driver name. |
Common Connection Options
| Constant | Description |
|---|---|
| PDO::ATTR_ERRMODE | Sets the error handling mode. Use PDO::ERRMODE_EXCEPTION to throw exceptions on errors. |
| PDO::ATTR_DEFAULT_FETCH_MODE | Sets the default fetch mode. Use PDO::FETCH_ASSOC to retrieve results as associative arrays. |
| PDO::ATTR_EMULATE_PREPARES | Set to false to use native prepared statements. Recommended for protection against SQL injection. |
| PDO::MYSQL_ATTR_INIT_COMMAND | Specifies an SQL command to run immediately after connecting to MySQL. Commonly used to set the character encoding. |
Sample Code
<?php
// Basic connection to MySQL.
$dsn = 'mysql:host=localhost;dbname=myapp;charset=utf8mb4';
$username = 'db_user';
$password = 'db_password';
try {
$pdo = new PDO($dsn, $username, $password);
echo "Connected successfully"; // Output on successful connection.
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
// Recommended connection setup using an options array.
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, // Throw exceptions on errors.
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, // Fetch results as associative arrays.
PDO::ATTR_EMULATE_PREPARES => false, // Use native prepared statements.
];
$pdo = new PDO($dsn, $username, $password, $options);
// Connect to SQLite. No credentials needed since it is file-based.
$pdo_sqlite = new PDO('sqlite:/path/to/database.db');
$pdo_sqlite->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Connect to PostgreSQL.
$pdo_pg = new PDO('pgsql:host=localhost;dbname=myapp', 'user', 'password');
// Retrieve server information.
echo $pdo->getAttribute(PDO::ATTR_SERVER_VERSION); // Outputs something like '8.0.36'.
echo $pdo->getAttribute(PDO::ATTR_DRIVER_NAME); // Outputs 'mysql'.
// A practical example of managing the connection as a class.
class Database
{
private static ?PDO $instance = null;
public static function getConnection(): PDO
{
if (self::$instance === null) {
$dsn = 'mysql:host=localhost;dbname=myapp;charset=utf8mb4';
self::$instance = new PDO($dsn, 'user', 'password', [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
]);
}
return self::$instance;
}
}
$pdo = Database::getConnection();
Notes
PDO stands for PHP Data Objects. It is a class that provides an abstraction layer for database access. Always set PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION when connecting. The default silent mode ignores errors, making debugging very difficult.
You can set the character encoding by specifying charset=utf8mb4 in the DSN. utf8mb4 supports 4-byte UTF-8 characters including emoji, so it is preferred over utf8.
To execute SQL, use prepared statements via PDO::prepare(). To retrieve results, use fetch() / fetchAll(). For transaction control, use beginTransaction(). For handling connection errors, see try / catch.
If you find any errors or copyright issues, please contact us.