Lesson 17 — Databases
Connecting to MySQL with PDO
PDO (PHP Data Objects) provides a consistent, secure interface for connecting PHP to a MySQL database and running queries against it.
Establishing a Connection
A PDO connection requires a Data Source Name (DSN) describing the database driver, host, and database name, along with credentials. Wrapping the connection in try/catch handles failures gracefully.
PHP — Connecting with PDO
try {
$pdo = new PDO(
"mysql:host=localhost;dbname=school_db;charset=utf8mb4",
"root",
""
);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
die("Connection failed: " . $e->getMessage());
}
Common Mistakes
- Hardcoding database credentials directly in a file that might be committed to version control or exposed accidentally.
- Forgetting to set PDO::ATTR_ERRMODE to ERRMODE_EXCEPTION, missing helpful error details when something goes wrong.
- Not specifying a charset in the DSN, which can cause issues with special characters and emoji.
- Using the older mysqli or mysql_* functions in new code when PDO offers a more consistent, driver-agnostic interface.
Professional Tip
Store database credentials in environment variables or a configuration file kept outside version control, rather than hardcoding them directly in your PHP scripts.
Your Turn
Set up a local MySQL database and write a PHP script that establishes a PDO connection to it, printing a success message if the connection works and a clear error otherwise.
Mini Quiz
What does PDO stand for in PHP?
PDO (PHP Data Objects) is a database access layer providing a consistent interface across different database systems, with MySQL being one of the most common.