MySQL/die() Alternative?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Toot4fun
Forum Commoner
Posts: 25
Joined: Wed Dec 10, 2003 11:44 am

MySQL/die() Alternative?

Post 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
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

store the error data in a session variable?
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: MySQL/die() Alternative?

Post 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
}
(#10850)
Toot4fun
Forum Commoner
Posts: 25
Joined: Wed Dec 10, 2003 11:44 am

Post 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.
Post Reply