Skip to content

Instantly share code, notes, and snippets.

@adrian-enspired
Last active November 17, 2021 03:16
Show Gist options
  • Save adrian-enspired/385c6830ba2932bc36a2 to your computer and use it in GitHub Desktop.
Save adrian-enspired/385c6830ba2932bc36a2 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!
];
$pdo = new PDO($dsn, $user, $pass, $options);
// now $pdo is ready for use!
// Note that if there's a problem here, the error message will probably contain your DB password.
// NEVER show exception messages to your user!
// MAKE SURE your php.ini file contains display_errors = 0
// Note there is NO try..catch block in this example.
// If you only want to log the error, note that PHP can do that on its own, without your catching the exception.
// learn more here: https://phpdelusions.net/pdo#errors
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment