PHP - Find errors fast by triggering errors where you want, not where php puts them
In the case of connecting to MySQL in a PHP script, usually a fatal error will tell you where you provided invalid connection info (i.e. wrong password), this is the file and line where the mysql_connect() function is called.
This is not useful if you use a php class to deal with the database connection. The error message will show the file and line where the mysql_connect() function is (and it is always the same place, within the database class!)
It turns out that this is not where the wrong password is provided to the class, so it can take some time to find the file and line where you send the credentials to MySQL.
To find the line where you actually provided the wrong password:
1. First, suppress the fatal error with the @ symbol.
2. Then, check if there is an error. If so, store the error and then trigger the error outside of the class.
/* Index.php */
$db = new MySQL($host,$user,$password,$dbName);
if($db->dbError){trigger_error($db->dbError,512);}/* mysql.class.php */
class MySQL{
var $db;function __construct($host, $dbUser, $dbPass, $dbName) {
// or the old school constructor: function MySQL($host, $dbUser, $dbPass, $dbName) {
$this->host=$host;
$this->dbUser=$dbUser;
$this->dbPass=$dbPass;
$this->dbName=$dbName;
$this->dbError=FALSE;
$this->connectToDb();}
// connection method
function connectToDb(){if (!$this->dbConn = @mysql_connect($this->host, $this->dbUser, $this->dbPass)) {
$this->dbError=’Error connection to database: ‘.mysql_error();
return;
}// … check if database can be selected in the same way
}
Note 1: this does not work if it is normal for the function to return bool (a value that equates to false)
Note 2: if you use a custom error handler you need to have the following to suppress the error
function errorHandler($errno, $errdetails, $errfile = null, $errline = null, $errcontext = null)
{// check for error suppression
if(error_reporting()==0){
return;
}
// continue processing the error here}
With custom functions you can use the following error() function instead of trigger_error()
function error($message, $level=E_USER_NOTICE)
{$dbk=debug_backtrace();
$caller = next($dbk);
trigger_error($message.’ in ‘.$caller['function'].’.’.$caller['file'].’ ‘.$caller['line'].”\n
error handler”, $level);}
Example use:
function custom($val)
{if(!is_array($val)){
error(’You must provide an array to the custom function’);
} else {
// do whatever
}}
Subscribe by RSS