Created
April 9, 2012 20:25
-
-
Save nikoheikkila/2346388 to your computer and use it in GitHub Desktop.
PHP: Using PDO_MYSQL driver
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 | |
/** | |
* 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