PDO Database Connection Script with Email on Error

Posted By: Ian on Dec 18, 2012 in PDO, PHP, Snippets
Last modified on May 30th, 2014 at 5:51 pm,

PDO Connection is seen as the way to go it has a lot of advantages over other techniques and today i share with you a script i mostly use for connecting to my databases as for 1 i get an email with the page and section if something goes wrong and for 2 the visitor sees a polite message asking them to try there request later.


* PDO database connection script with email upon error and the use of sections to make errors easier to fix
* Sections are only useful if code is wrapped in a try catch block
* Ian.J.Gough - webmaster@ianjgough.com
* ianjgough.com
* December 18th 2012

* Define some constants
* Minimum changes needed are USERNAME, PASSWORD and DATABASE NAME

define('EMAIL_TO', 'webmaster@yourdomain.com');
define('EMAIL_FROM', 'alert@yourdomain.com');
define('DB_TYPE', 'mysql');
define('DB_HOST', 'localhost');
define('DB_USER', 'USERNAME');
define('DB_PASS', 'PASSWORD');

* Get Current URL (Secure and Non Secure sites).
* Taken from
* http://myphpscriptz.com/2010/10/how-to-get-the-url-of-the-current-page-using-php-server-variables/
function getURL()
$url = 'http';
if ($_SERVER["HTTPS"] == "on") {
$url .= "s";
$url .= "://";
if ($_SERVER["SERVER_PORT"] != "80") {
} else {
return $url;

* This is our error function
* which on error will show our message
* and exit our application
function showError($section, $error)
echo "<h2>Error</h2>";
$content = "Sorry an error has occurred";
echo "$content <br />$error <br />Please try your request later";
$to = EMAIL_TO;
$subject = "Sorry an ERROR has occurred at " . getURL();
$message = "$content in section $section at " . getURL() . "rn$error rnAll the best, Ian.J.Gough";
$from = EMAIL_FROM;
$headers = "From:" . $from;
mail($to, $subject, $message, $headers);

* Section 1
* Create the connection object
* Set error reporting to throw exceptions
try {
$connect = new PDO(DB_TYPE . ":host=" . DB_HOST . ";dbname=" . DB_NAME, DB_USER, DB_PASS);
echo "Connected!";
catch (Exception $e) {
showError(("1"), ($e->getMessage()));

* Section 2
* Enter your query inside the try block { }
* Remember to use $connect to use our connection object defined earlier
try {

catch (Exception $e) {
showError(("2"), ($e->getMessage()));

The download contains 2 examples the one above and one with all the functions and constants in a configuration file (config.php).

Download Connection Script


Did this help you? Please Let me know by commenting below even if it’s just to say “Thanks”

Comments are closed.

About This Site

Dreams are built from lines of code well it's true!
If you can dream it you can usually code it.

I have learned so much from other people on the Internet and this site is for me to give back some of what i have learned and hope people can now learn from me.
Have fun and surf safely,

protected by copyscape duplicate content check


Powered by Banner Bar 125