Skip to content

Instantly share code, notes, and snippets.

@nikoheikkila
Created April 9, 2012 20:25
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 nikoheikkila/2346388 to your computer and use it in GitHub Desktop.
Save nikoheikkila/2346388 to your computer and use it in GitHub Desktop.
PHP: Using PDO_MYSQL driver
<?php
/**
* Example script for using PDO and MySQL
* Requires PHP >= 5.1
*
* @author Niko Heikkilä
* @version 1.0
*/
/* Set debug mode to silent, warning or exception */
$ERRMODE = "exception";
/* Used for logging */
$LOGFILE = "PDOErrors.log";
/* Replace these with your own */
$host = "localhost";
$dbname = "mydb";
$user = "bob";
$pass = "secret";
try {
/* Establish connection to database */
$DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
/* Set debugging level */
switch ($ERRMODE) {
case "warning":
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
break;
case "exception":
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
break;
case "silent":
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);
break;
default:
break;
}
}
catch (PDOException $e) {
/* Store errors in log file */
file_put_contents($LOGFILE, $e->getMessage(), FILE_APPEND);
die("Fatal error. See $LOGFILE for details.");
}
echo "Opened connection to database $dbname at $host";
/* Close the connection if open */
if ($DBH) {
$DBH = NULL;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment