Created
July 24, 2024 20:14
-
-
Save RobinBoers/a78370c454fdc6c1f9409edb911a10bd to your computer and use it in GitHub Desktop.
Function for establishing a MySQL database connection in PHP using PDO.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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