Skip to content

Instantly share code, notes, and snippets.

@RobinBoers
Created July 24, 2024 20:14
Show Gist options
  • Save RobinBoers/a78370c454fdc6c1f9409edb911a10bd to your computer and use it in GitHub Desktop.
Save RobinBoers/a78370c454fdc6c1f9409edb911a10bd to your computer and use it in GitHub Desktop.
Function for establishing a MySQL database connection in PHP using PDO.
function establish_connection() {
$host = DB_HOST;
$user = DB_USER;
$pass = DB_PASS;
$name = DB_NAME;
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$dsn = "mysql:host=$host;dbname=$name;charset=utf8mb4";
try {
return new PDO($dsn, $user, $pass, $options);
}
catch(PDOException $e) {
die("Database connection failed: " . $e->getMessage());
}
}
define('DBH', establish_connection());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment