Connecting PHP to MySQL Using PDO
Most data-driven PHP applications need to communicate with a database. PDO (PHP Data Objects) provides a consistent interface for working with different database systems. With the MySQL PDO driver installed, it can connect to MySQL and MariaDB.
Creating a Connection
Keep database credentials outside publicly accessible directories and load them from protected configuration. A basic connection looks like this:
$dsn = "mysql:host=localhost;dbname=app_db;charset=utf8mb4";
$pdo = new PDO($dsn, $dbUser, $dbPassword, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);
Use the actual host, database name, username, and password for your environment. The utf8mb4 character set supports a broad range of Unicode characters.
Using Prepared Statements
Do not concatenate untrusted values into SQL strings. Prepare a statement and pass values separately:
$stmt = $pdo->prepare(
"SELECT id, title FROM articles WHERE slug = :slug LIMIT 1"
);
$stmt->execute(["slug" => $slug]);
$article = $stmt->fetch();
This separates SQL structure from parameter values and helps prevent SQL injection. Placeholders represent values, not table or column names; dynamic identifiers require a strict allowlist.
Handling Errors
PDO can throw exceptions when a database operation fails. Catch exceptions at an appropriate application boundary, log technical details privately, and show visitors a generic error message. Never expose database credentials or raw exception details in public responses.
Good Practices
Use a least-privilege database account, keep credentials outside the web root, use HTTPS, validate application input, and back up important data. Reuse a well-configured connection rather than duplicating connection logic throughout the project.
Conclusion
PDO offers a clean and secure foundation for PHP database access. Prepared statements, protected configuration, and careful error handling should be standard parts of every database-driven application.