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.
$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.
<?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();
}
?>Connected successfullyA PDO object is created and configured to throw exceptions on database errors.
<?php
try {
$pdo = new PDO("mysql:host=localhost;dbname=missingdb", "root", "wrongpass");
} catch (PDOException $e) {
echo "Connection failed";
}
?>Connection failedAn 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.
