Skip to content

Instantly share code, notes, and snippets.

@kartagis
Forked from adrian-enspired/PDO_mysql.connect.php
Created August 23, 2016 16:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kartagis/eab4174f2e730054c7d2d4a83f46e1cb to your computer and use it in GitHub Desktop.
Save kartagis/eab4174f2e730054c7d2d4a83f46e1cb to your computer and use it in GitHub Desktop.
how to make a new mysql connection with PDO.
<?php
$host = "db hostname";
$dbname = "db name";
$user = "db username";
$pass = "db password";
$charset = "UTF8MB4"; // if your db does not use CHARSET=UTF8MB4, you should probably be fixing that
$dsn = "mysql:host={$host};dbname={$dbname};charset={$charset}";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, // highly recommended
PDO::ATTR_EMULATE_PREPARES => false // ALWAYS! ALWAYS! ALWAYS!
];
try {
$pdo = new PDO( $dsn, $user, $pass, $options );
// now $pdo is ready for use!
} catch ( PDOException $e ) {
// always catch PDOExceptions.
// If there's a problem here, the error message will probably contain your DB password.
// log the error.
// during development, if your server is not public, you can display the message instead if you prefer.
error_log( $e->getMessage() );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment