Page 1 of 1
MySQL/die() Alternative?
Posted: Wed Apr 05, 2006 8:56 am
by Toot4fun
When executing MySQL commands in my PHP pages, I have code similar to the following:
Code: Select all
$strQuery = "SELECT * FROM myTable WHERE status='trial' ORDER BY name";
$strResults = mysql_query($strQuery) or die('Query failed.<br>MySQL Error Number: ' . mysql_errno() . '<br>MySQL Error Description: ' . mysql_error());
I'd like to know if there's a way to redirect to an error page instead of using the die() function. Any suggestions on handling MySQL errors would be greatly appreciated.
Thank you,
Brian
Posted: Wed Apr 05, 2006 10:21 am
by feyd
store the error data in a session variable?
Re: MySQL/die() Alternative?
Posted: Wed Apr 05, 2006 12:04 pm
by Christopher
I still see this kind of code all the time and it really is a poor coding practice. I suppose that those kinds of error message were ok in the early days of the web (when PHP was young), but not today. Better would be:
Code: Select all
$sql = "SELECT * FROM myTable WHERE status='trial' ORDER BY name";
$result = mysql_query($sql)
if (mysql_error($result)) {
$errmsg = 'Query failed.<br>MySQL Error Number: ' . mysql_errno() . '<br>MySQL Error Description: ' . mysql_error();
// save that message to a log somewhere
// then either build the error page/view here or redirect to an error page
} else {
// you may want a numrows > 0 check here (if so then you will need a "no results" page/view
// fetch rows
// then build the page/view here
}
Posted: Wed Apr 05, 2006 1:51 pm
by Toot4fun
I completely agree with Christopher. I know that code was very weak, but it served the purpose at the time. Now that I have some time to recode, it's time to do it right.
Thanks for your help.