PHP ยท Chapter 41 of 44

PHP MySQL Connect with PDO

PDO (PHP Data Objects) is a database access layer that provides a consistent interface for working with different database systems, including MySQL. Using PDO makes it easier to switch databases later and encourages secure coding practices like prepared statements.

To connect to a MySQL database with PDO, you create a new PDO object with a Data Source Name (DSN) string, a username, and a password, and it's good practice to wrap the connection in a try/catch block to handle connection errors.

Syntax
$pdo = new PDO("mysql:host=localhost;dbname=mydb", $user, $pass);

Creating a PDO connection

new PDO("mysql:host=localhost;dbname=mydb", $user, $pass) opens a connection. Setting the error mode to exception mode helps you catch connection and query problems reliably.

Handling connection errors

Wrapping the connection code in try/catch (PDOException $e) lets you gracefully report a failed connection instead of exposing raw errors to users.

Example 1 (php)
<?php
try {
  $pdo = new PDO("mysql:host=localhost;dbname=testdb", "root", "");
  $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  echo "Connected successfully";
} catch (PDOException $e) {
  echo "Connection failed: " . $e->getMessage();
}
?>
Output
Connected successfully

A PDO object is created and configured to throw exceptions on database errors.

Example 2 (php)
<?php
try {
  $pdo = new PDO("mysql:host=localhost;dbname=missingdb", "root", "wrongpass");
} catch (PDOException $e) {
  echo "Connection failed";
}
?>
Output
Connection failed

An invalid database name or credentials causes PDO to throw a PDOException, caught here safely.

Key points

  • PDO provides a consistent interface for multiple database systems.
  • A PDO connection is created with a DSN string, username, and password.
  • Setting ATTR_ERRMODE to ERRMODE_EXCEPTION enables proper error handling.
  • Always wrap database connections in try/catch to handle failures gracefully.
๐Ÿ’ก Note: Never hardcode real database credentials directly in source files that might be shared or committed publicly โ€” use environment variables instead.

๐Ÿ“ Quick Quiz

1. What does PDO stand for?

2. What three things does creating a PDO connection require?

3. What exception type does PDO throw on connection errors?