PHP

The classic way to handle errors in PHP is to stop the script when something goes awry.

Review Eddo Rotman's slides and decide about error vs. exception distinction.

$dbc = mysql_connect('127.0.0.1','root','********') or die( mysql_error() );
mysql_select_db ('engl') or die( mysql_error() );

This abrupt form of seppuku is better than nothing. Your code can cough out an error message in its death rattle, but it litters your code with multiple exit points.

PHP now supports try / catch blocks. These are slower to process, but they allow you to consolidate your error handling and to exit your script in a controlled manner.

try / catch

When PHP throws an exception, it stops executing the current block and jumps to the next catch(). Only one throw will occur in a try block.

try {
	$dbc = new mysqli('localhost','root','mysql4engl','engl');/* create $dbc object */
	if ($dbc->connect_errno) {/* check for error */
		throw new Exception("Failed to get data.");
	}
	$sql="select concat(Last, ', ', First) as name, uwnetid, from people";
	$result = $dbc->query($sql);/* create $result object */
	if ($dbc->affected_rows == -1) {/* if ($result) would work, too */
		throw new Exception("Failed to comprehend");
	}
	while($row = $result->fetch_assoc()) echo "\n{$row['name']}, <{$row['uwnetid']}@uw.edu>";
}
catch (Exception $e) {
	echo "\n{$e->getMessage()}\n\n";
}

A mysqli object stores error information as public properties.

An Exception object can take 3 arguments (all optional):

Its constructor method automatically records:

These can be retrieved as:

(Because the line that throws always follows the code that caused the exception, it makes sense to keep things proximate: i.e., test for failure and throw in the "then" block, rather than test for success and throw in an "else" block.)

Attackers can make use of specific error messages, so you want to show generic messages to users when things go awry.

define( 'DATA_ERR', 1 );
define( 'RIGHTS_ERR', 2 );
define( 'SRCH_ERR', 3 );

Example: Throw an Exception with a specific message and a generic error code:

throw new Exception( "Ack! {$dbc->connect_errno}: {$dbc->connect_error}", DATA_ERR );

Process the Exception based on error code:

catch (Exception $e) {
	switch ( $e->getCode ) {
		case DATA_ERR:
			$msg='Data error.';
			break;
		case RIGHTS_ERR:
			$msg='Permission error.';
			break;
		case SRCH_ERR:
			$msg='Nothing found.';
			break;
		default:
			$msg='Aw Shucks.';
	}
	$display->usermsg($msg);/* a possible message handling object */

	$email = 'coder@uw.edu';
	$subj = 'PHP errtype ' . $e->getCode();
	$msg = date('Y-m-d') . 'thrown on line ' . $e->getLine() . "\n" . $e->getMessage() . "\n" .
		'file: ' . $_SERVER['SERVER_NAME'] . '/' . $e->getFile();
	mail( $email, $subj, $msg );
}

Instead of, or in addition to, mailing, you could write to a custom log file or web page.

For more, see Eddo Rotman's Elegant Ways of Handling PHP Errors and Exceptions