Example
<?php
$host = '127.0.0.1';
$dbname = 'app_database';
$username = 'app_user';
$password = 'replace-with-secret';
$dsn = "mysql:host={$host};dbname={$dbname};charset=utf8mb4";
try {
$pdo = new PDO($dsn, $username, $password, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
]);
} catch (PDOException $exception) {
error_log($exception->getMessage());
http_response_code(500);
exit('A database error occurred.');
}
Explanation
PDO provides a consistent interface for database access. The connection uses utf8mb4, exception-based error handling, and associative fetches.
Production advice
Move credentials to a configuration file outside the public web root or to environment variables. Do not display database exception details to visitors.