WeberDev.com PHP and MySQL Code

LOG IN
BEGINNER GUIDES  |  PHP CLASSES  |  CODE SEARCH  |  ARTICLES SEARCH  |  PHP FORUMS  |  PHP MANUAL  |  PHP FUNCTIONS LIST  |  WEB SITE TEMPLATES
Start typing to search for PHP and MySQL Code Snippets and Articles Search
Submit a code Example / Snippet Submit Your Code
Search Engine Optimization Monitor SEO Monitor
Web Site UpTime Monitor UpTime Monitor
WeberDev's Monthly code contest PHP Code Contest
Your Personal Examples List My Favorite Examples
Your Personal Articles List My Favorite Articles
Edit Account Info Update Your Profile
PHP Code Search
Web Development Forums
Learn MySQL Playing Trivia
PHPBB2 Templates
Web Development Index
Web Development Resources
Web Development Content
PHPClasses
PHP Editor
PHP Jobs
Vision.To Design
Ajax Tutorials
PHP Programming Help
PHP/MySQL Programming
Webmaster Resources
Webmaster Forum
XML meta language
website builder
Mobile Dev World

Go Back Add a Comment Send this example to a friend Add this Article to your personal favoritest for easy future access to your favorite Code Examples and Articles. Submit a code example Print this code example.
BACK ADD A COMMENT SEND TO A FRIEND ADD TO MY FAVORITES ADD CODE EXAMPLES PRINT
Title : DB Connection Function with error handling and email failure notices
Categories : PHP, MySQL, Errors and Logging, Databases, Errors and Logging Click here to Update Your Picture
bastien koert
Date : Aug 27th 2004
Grade : 3 of 5 (graded 3 times)
Viewed : 9497
File : No file for this code example.
Images : No Images for this code example.
Search : More code by bastien koert
Action : Grade This Code Example
Tools : My Examples List

  Submit your own code examples 
 

This is my standard approach to db connectin. I create a connection file called conn.php and place it outside the root folder (something like /myconfig/conn.php). Then i include this file into any file i need that has db access ... see code below.

This code does manage to fail a little more gracefully than others and will send out an email notification to you so that you can see what crashed and why.

Placing the code into a function will also make it more secure and simpler to call. There is some basic security in the file. The first time this is run, it will likely fail and present a message saying

"piss off, hackers".

Above that there is the line 'server is:' and some name, likely the website name (yourdomain.com / yourdomain.ca, whatever)copy the name and paste it back into the conn.php where it currently says 'localhost'...if no error comes up then the code is fine...then comment out the echo line.

Its easy to add further checks to prevent inclusion by other users. Sessions is one.





<?php
//conn.php

 
bastien koert
  Aug 2004
  www
.bastienkoert.net



this domain
-- this check may take a little configuration to get the correct host name

use this the first time to get the host name...then comment it out or delete to complete the security check  */

//echo "server is : ".$_SERVER['SERVER_NAME']."<br>";

if (($_SERVER['SERVER_NAME']!="localhost")){
   echo
"piss off, hackers!";
  die();
}
function
conn($sql)
{
$host = "myhost";       /* change these to match your situation */
$user = "myusername";
$pass = "mypassword";
$db   = "mydb";

    if (!(
$conn=mysql_connect($host, $user, $pass)))  {
       
printf("Error connecting to DB");
       
email_error("connection",mysql_error());
    }
    if (!(
$db3=mysql_select_db($dbname,$conn))){
       
printf("<p>Error connecting to DB");
       
email_error("Connection Error",mysql_error());
    }

   
$result = mysql_query($sql);

    if (
mysql_errno() == 0){
      return
$result;
    }else{
     
email_error($sql,mysql_error());
     
$result = 'Null';
    }
}
//end function

function email_error($reason, $error)
{
   
$headers = "MIME-Version: 1.0\n";
   
$headers .= "Content-type: text/plain; charset=iso-8859-1\n";
   
$headers .= "X-Priority: 3\n";
   
$headers .= "X-MSMail-Priority: Normal\n";
   
$headers .= "X-Mailer: php\n";
   
$headers .= "From: \"".$from."\" <".$from.">\n";


   
$sendto = "me@mydomain.com";
   
$subject = "Db error notification";

   
$time = date("Y-m-d H:m");

   
$message = "Application db interface failed at $time.\n\n
                Operation : $reason\n\n
                MySQL Error: $error \n\n
                User: "
.$_SESSION['username']."\n\n

                Regards,

                System"
;

   
mail($sendto, $subject, $message, $headers);

    die(
"<p>There was a problem with the database");
}
?>


To use this file, you include it and then simply call the function


CODE FOR IMPLEMENTAION IN ASSOCIATED FILES
<?php
//include conn file
require("config/conn.php");

//more of your code

$sql = "select * from tableName [where][group by][order by]";

// get the regular listing results
$result = connect($sql);

if (
$result){

//show the results
}else{
 
//handle failure in some way
}
?>



Visits-tracking
Categories : PHP, Databases, MySQL, Errors and Logging, Functions
bookmarker - PHP, PHPLIB, MySQL WWW based bookmark manager
Categories : MySQL, PHP, MySQL, Complete Programs, Databases
This program allows you to upload an ODBC ressource - i.e. an MS-Access database to a MySQL server.
Categories : Databases, MySQL, Complete Programs, PHP, Databases
AJAX Data Grid System using php and mysql. A complete login system with the ability to display data in a grid using ajax. Add , update and delete the records without reloading the page.
Categories : PHP, AJAX, Databases, MySQL, Java Script
Identify and log search engine access (spiders, robots, etc.) to a page.
Categories : HTTP, Environment Variables, PHP, MySQL, Databases
A simple script to count and report hits and the last modification time of an HTML page. Requires MySQL support (other DBs should work too, except possibly mSQL).
Categories : HTTP, MySQL, PHP, Databases
create a grid out of <INPUT TYPE=TEXT> then saving to a database. Uses a 'multi-dimension array', but not really as the array is just one big array with the index of "[$i][$j]". Have a look at the code and you'll see what I mean.
Categories : PHP, MySQL, Arrays, Databases
php-gtk mysql querying tool
Categories : PHP-GTK, MySQL, PHP, Databases
Simple function to return the number of days in a time span between 2 given dates.
Categories : PHP, Date Time, MySQL, Databases
Solution to those 'tell-a-friend' type email issues
Categories : PHP, Email, Databases, MySQL
PostGreSQL and MySQL 2 in 1 db Manager
Categories : PHP, PHP Classes, Databases, PostgreSQL, MySQL
mediaCat-GTK v2.0.0 - an mp3/cd/dvd cataloging utility written in php-gtk which interfaces with mysql and ms access (or db supported by PHP's Unified ODBC Functions)
Categories : PHP, MySQL, MS Access, Utilities, Databases
[PHP5] aDB PDO LIKE Database Abstraction. Switch easily from one db server to another, strong errors management, manage transactions, queries preparation and more.
Categories : PHP, PHP Classes, Databases, MS SQL Server, MySQL
Pull Down Surfing - Surf on Change
Categories : Java Script, MySQL, HTML and PHP, PHP, Databases
Example of function to send out email if error occurs
Categories : PHP, Email, Debugging, Errors and Logging