Last active
June 22, 2019 04:56
-
-
Save fiko/ca5faf9e2fc469d93ebcfca7c917de76 to your computer and use it in GitHub Desktop.
PHP script to connect to database using PDO library/class
This file contains 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
<?PHP | |
$config = [ | |
'DB_HOSTNAME' => 'localhost', | |
'DB_USERNAME' => 'root', | |
'DB_PASSWORD' => 'rootpassword', | |
'DB_DATABASE' => 'dummy_database' | |
]; | |
$dsn = "mysql:host={$config['DB_HOSTNAME']};dbname={$config['DB_DATABASE']};charset=utf8mb4"; | |
$options = [ | |
PDO::ATTR_EMULATE_PREPARES => false, // turn off emulation mode for "real" prepared statements | |
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, // turn on errors in the form of exceptions | |
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, // make the default fetch be an associative array | |
]; | |
try { | |
$this->conn = new PDO($dsn, $config['DB_USERNAME'], $config['DB_PASSWORD'], $options); | |
} catch (Exception $e) { | |
error_log($e->getMessage()); | |
exit('Something weird happened'); // something a user can understand | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment