Using PHP Objects to Access Your Database Tables (Part 1)
By Tony Marston2005-04-05
Standard functions
These are some standard functions which I use throughout my software and which can be tailored for use in any application.
db_connect
This is the contents of my 'db.inc' file which I include in every script. As well as opening a connection to your MySQL server it will select the desired database.
$dbconnect = NULL;Error Handler
$dbhost = "localhost";
$dbusername = "****";
$dbuserpass = "****";
$query = NULL;
function db_connect($dbname)
{
global $dbconnect, $dbhost, $dbusername, $dbuserpass;
if (!$dbconnect) $dbconnect = mysql_connect($dbhost, $dbusername, $dbuserpass);
if (!$dbconnect) {
return 0;
} elseif (!mysql_select_db($dbname)) {
return 0;
} else {
return $dbconnect;
} // if
} // db_connect
This is the contents of my 'error.inc' file which I include in every script. It contains my universal error handler which traps every error, and for fatal errors it will display all relevant details on the screen and stop the system. In the event of a database error it will display the contents of the last $query string.
set_error_handler('errorHandler');
function errorHandler ($errno, $errstr, $errfile, $errline, $errcontext)
// If the error condition is E_USER_ERROR or above then abort
{
switch ($errno)
{
case E_USER_WARNING:
case E_USER_NOTICE:
case E_WARNING:
case E_NOTICE:
case E_CORE_WARNING:
case E_COMPILE_WARNING:
break;
case E_USER_ERROR:
case E_ERROR:
case E_PARSE:
case E_CORE_ERROR:
case E_COMPILE_ERROR:
global $query;
session_start();
if (eregi('^(sql)$', $errstr)) {
$errstr = "MySQL error: $MYSQL_ERRNO : $MYSQL_ERROR";
$MYSQL_ERRNO = mysql_errno();
$MYSQL_ERROR = mysql_error();
} else {
$query = NULL;
} // if
echo "<h2>This system is temporarily unavailable</h2>\n";
echo "<b>><font color='red'>\n";
echo "<p>Fatal Error: $errstr (# $errno).</p>\n";
if ($query) echo "<p>SQL query: $query</p>\n";
echo "<p>Error in line $errline of file '$errfile'.</p>\n";
echo "<p>Script: '{$_SERVER['PHP_SELF']}'.</p>\n";
echo "</b></font>";
// Stop the system
session_unset();
session_destroy();
die();
default:
break;
} // switch
} // errorHandler
Tutorial Pages:
» Intended Audience
» Prerequisites
» An introduction to OO functionality within PHP
» My 'database_table' class
» Using this Class
» Standard functions
» Summary
