$sql = "SELECT Client FROM booked WHERE Name = 'larry'";
$result = mysql_query($sql) OR die('[MYSQL ERROR] - ['.mysql_errno().']<br />'.mysql_error());
while ( list($client) = mysql_fetch_row($result) ) {
echo "{$client}<br />\n";
}
I agree with this logic overall. The above is of course just oversimplified demo code, but I'd like to mention a few details I would change before putting this into practice.
The syntax "$result = mysql_query($sql) OR die();" is nicely compact but obfuscates the program logic. PHP is not actually ORing two values, it's halting execution halfway through the statement if mysql_query() returns true. This constitutes a hack because it depends entirely on the way the parser processes code rather than on explicit elements of the language. To help keep legacy code from crashing with PHP version X I'd break this into two statements: run the query, then act on the result. The parser won't care, and your code will be more easily readable by us humans.
Displaying mysql_error() is great for the developer but in a public application will expose the names of tables and fields to the public who shouldn't really see your wires and pipes.
mysql_error() doesn't usually contain the entire query and doesn't always contain the segment of the query that actually caused the error, so I always add the full query to the error message to save time in debugging.
Finally, die()ing on a mysql error is pretty harsh; a friendlier application would return the error state to parent layers, translate the error into advice a non-technical user can deal with, and display it in a way that doesn't crash the page.
Rather than trying to remember to go through the code later fixing these bits, I suggest adopting a convention early on that suits both development and publication, such as:
_______________________________
define('bDebug', true);
...
$bResult = mysql_query($sql);
if (!$bResult) return ReportSQLError('checking user name', mysql_errno(), mysql_error(), $sql);
...
function ReportSQLError($context, $errno, $errorMsg, $sql)
{
if (bDebug)
{
die("MYSQL ERROR $errno $context:<hr />\n$errorMsg<hr />\n$sql");
}
else
{
return $generate_friendly_error_message;
}
}
_______________________________
Regards,
Paul
__________________________
Paul Novitski
Juniper Webcraft Ltd.
http://juniperwebcraft.com