PLEASE HELP, learning PHP PDO, just need an explanation... DESPERATE.

I am learning PHP PDO from a book and I have had to create a file error_handler.php
I understand half it up until the static Handler function sets the variable $backtrace = GetBackTrace(2); ( line 21 ).

It looks like it takes the (2) as an argument which maybe means its working with the 3rd entry of the debug_backtrace array?? eg debug_array(2)??? I’m not sure what that is… I was thinking that it could be the ErrorHandler::SetHandler function as and array but if it is I can’t work out anything further.

Could someone please please please explain what is happening in the Get Back Trace function, i’m going crazy looking at. Broken down for the ultra beginner would be much appreciated.

class ErrorHandler
// Private constructor to prevent direct creation of object
private function __construct()

	/* Set user error-handler method to ErrorHandler::Handler method */
	public static function SetHandler($errTypes = ERROR_TYPES)
		return set_error_handler(array ('ErrorHandler', 'Handler'), $errTypes);
	// Error handler method
	public static function Handler($errNo, $errStr, $errFile, $errLine)
		/* The first two elements of the backtrace array are irrelevant:
		- ErrorHandler.GetBacktrace
		- ErrorHandler.Handler */
		$backtrace = ErrorHandler::GetBackTrace(2);
		// Error message to be displayed, logged, or mailed
		$error_message = "\nERRNO: $errNo\nTEXT: $errStr" .
			"\nLOCATION: $errFile, line " .
			"$errLine, at " . date('F j, Y, g:i a') .
			"\nShowing backtrace:\n$backtrace\n\n";
		// Email the error details, in case SEND_ERROR_MAIL is true
		if (SEND_ERROR_MAIL == true)
			error_log($error_message, 1, ADMIN_ERROR_MAIL, "From: " .
		// Log the error, in case LOG_ERRORS is true
		if (LOG_ERRORS == true)
			error_log($error_message, 3, LOG_ERRORS_FILE);
		/* Warnings don't abort execution if IS_WARNING_FATAL is false
		E_NOTICE and E_USER_NOTICE errors don't abort execution */
		if (($errNo == E_WARNING && IS_WARNING_FATAL == false) ||
		($errNo == E_NOTICE || $errNo == E_USER_NOTICE))
		// If the error is nonfatal ...
			// Show message only if DEBUGGING is true
			if (DEBUGGING == true)
				echo '<div class="error_box"><pre>' . $error_message . '</pre></div>';
		// If error is fatal ...
			// Show error message
			if (DEBUGGING == true)
				echo '<div class="error_box"><pre>'. $error_message . '</pre></div>';
			// Stop processing the request
	// Builds backtrace message
	public static function GetBackTrace($irrelevantFirstEntries)
		$s = '';
		$MAXSTRLEN = 64;
		$trace_array = debug_backtrace();
		for ($i = 0; $i < $irrelevantFirstEntries; $i++)
		$tabs = sizeof($trace_array) - 1;
		foreach ($trace_array as $arr)
			$tabs -= 1;
			if (isset ($arr['class']))
				$s .= $arr['class'] . '.';
			$args = array ();
			if (!empty ($arr['args']))
				foreach ($arr['args']as $v)
					if (is_null($v))
						$args[] = 'null';
					elseif (is_array($v))
						$args[] = 'Array[' . sizeof($v) . ']';
					elseif (is_object($v))
						$args[] = 'Object: ' . get_class($v);
					elseif (is_bool($v))
						$args[] = $v ? 'true' : 'false';
						$v = (string)@$v;
						$str = htmlspecialchars(substr($v, 0, $MAXSTRLEN));
						if (strlen($v) > $MAXSTRLEN)
						$str .= '...';
						$args[] = '"' . $str . '"';
			$s .= $arr['function'] . '(' . implode(', ', $args) . ')';
			$line = (isset ($arr['line']) ? $arr['line']: 'unknown');
			$file = (isset ($arr['file']) ? $arr['file']: 'unknown');
			$s .= sprintf(' # line %4d, file: %s', $line, $file);
			$s .= "\n";
		return $s;


My suggestion to you would be to find a different book on PHP PDO, for that code is using object-oriented programming style. I also find that code to be poppycock, I simply throw exceptions like:

[php]try {

$query = 'Select id, creatorId, title, content, DATE_FORMAT(dateUpdated, "%e %M %Y") as dateUpdated FROM pages WHERE sticky="sysop" ORDER BY dateAdded DESC LIMIT 200';
$result = $pdo->query($query);

// Check that rows were returned:
if ($result && $result->rowCount() > 0) {
	// Set the fetch mode:
	$result->setFetchMode(PDO::FETCH_CLASS, 'Page');
	// Records will be fetched in the view:
} else { // Problem!
	throw new Exception('No content is available to be viewed at this time');

} catch(Exception $e) { // Catch generic exceptions

You just want to know why the code isn’t working with something in a database (at least a general idea) and in this case this particular code looks like some kind of mail handler which might but probably doesn’t have anything to do with PDO. My opinion people spend to much time worry about “potential” errors than getting the code to work. If you just isolate the errors without crashing the rest of the code then you have accomplished something. :wink:

I agree with Strider64. First, you mention you are a beginner learning PDO.

Do you know PHP? PDO_MYSQL is a driver that implements the PHP Data Objects (PDO).
So, to learn PDO, you have to know PHP to a good level and also MySQL to a good level.

But, your routine:

/* The first two elements of the backtrace array are irrelevant:

  • ErrorHandler.GetBacktrace
  • ErrorHandler.Handler */
    $backtrace = ErrorHandler::GetBackTrace(2);

Tells you exactly why it is using the ‘2’. It is skipping the BackTrace(0) and BackTrace(1) because they are irrelevant for this use. So, it skips them and go to the third array entry, #2. Hope that helps…

I’ve been learning PHP for a little while now, definitely a beginner hence why i need an explanation on something so trivial. I stopped focusing on mysqli and chose to learn PDO as it seemed better to grasp now rather than later. Good idea im still not sure??

Anyway, the code works as its from a book, hence the notes that explain what its doing but i just can’t grasp the debug_backtrace and what information it is returning for first two arrays that it skips by putting ‘2’ in the brackets. I echo’d it out but it didn’t seem relative to anything.

I know if seems silly but if you can explain this a bit better that would be amazing.

Well, usually to learn PHP, you learn just HTML, JS, MySQL(or MySQLi) and PHP. Then, later on you learn the add-on’s and plugin’s as needed. I have been programming HTML, JS, MySQL and PHP for years. I seldom use MySQLi as regular MySQL is easier. (for me) I know about PDO, but, have never really used it as I do not need to do much programming in Object-Orientated systems. They say it is best to learn about Object-Orientated systems for many various reasons. So, usually, I would suggest starting with just PHP and MySQL. Once mastered, head on to Object-Orientated PHP and MySQLi. Doesn’t really matter as you seem to grasp the basics of all of these.

Now back to your question. A lot of OO systems have programming that is there “just in case”. It appears this book is teaching you how to trace errors and keep records of them for fixing them.

You have an ErrorHandling Class. It tracks errors, I would guess as they happen elsewhere in the program as they occur. So, other places in the program it calls the ErrorHandling Class. In this class it keeps an array of errors. It also, keeps an array of details of the error and another of error types. Then, it has a “handler” for each type of error. It appears only partially there.

So, to understand what this class does in the grand scheme of things? Well, first you have to understand the entire program. We do not have that so… And, next, you need to know what the author of the program is trying to do with all the code. We do not know that. If we had the book in hand, I am sure several of us here would give you a great answer.

This site works best for people writing their own code as we can ask the correct question to them. Hard to ask the writer of some book what they were trying to do. As Strider64 stated, this is code for potential errors and it is hard to help study something that has not happened. Error handlers are different for each program. There is no one solution for all programs. So, without learning the entire program, this is just a sample of an error handler and means nothing unless it has a program that goes with it. Did that make sense? Better to spend your time learning PDO or just PHP than error handler code that doesn’t work with a program… Good luck…

Sponsor our Newsletter | Privacy Policy | Terms of Service