PDO Connection
Wrap PDO connection in try/catch to handle connection failures. Set error mode to exceptions so PDO throws on errors rather than returning false.
Wrap PDO connection in try/catch to handle connection failures. Set error mode to exceptions so PDO throws on errors rather than returning false.
<?php
function createConnection(): PDO {
$dsn = "mysql:host=localhost;dbname=mydb;charset=utf8mb4";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false, // Use real prepared statements
];
try {
return new PDO($dsn, "dbuser", "dbpass", $options);
} catch (PDOException $e) {
// Log error internally, show generic message to user
error_log("DB Connection failed: " . $e->getMessage());
throw new RuntimeException("Database unavailable", 503, $e);
}
}
Always set ATTR_EMULATE_PREPARES to false — it ensures real prepared statements are used instead of emulated ones.