Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

or die("Is there a better way to do this?")

Status
Not open for further replies.

dwessell

Programmer
Jan 26, 2006
114
US
Hey all, when interacting with mySQL.. Is there a better way to go about recovering from a query error?

mysql_query($Query) or die("Query error");

Say redirecting to a error page, making the user begin over with filling out the form? Appreciate any thoughts.


Thanks
David
 
You can do whatever you want inside the die statement.
Issue a custom message, redirect using the header command,( if nothing has been output to the browser prior to this call) you can even call a function to display a custom error page or something.

Code:
...or die(header("Location:errorpage.php"));
...
...or die(myerrorhandlingfuntion());
etc...

if the query fails for whatever reason, this will send the suer to a custom error page. Again provided that nothing has been utput to the browser prior to this.




----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.
 
is there a better way? that depends what you want to achieve. if you want your code to bail out on a sql error then die() or exit() might be all you need. they are very useful for debugging, for sure.

if the sql call just picks up a small part of your page then you might want the call to fail-soft rather than kill your whole app. in which case an if construction might be more elegant, with a logging of the error in some sensible log so that you can fix it later.

My recommendation would be to write a custom error handling class or set of procedures that manages all your (non-php-critical) errors. or use the PEAR error handling system (which I use when I make use of a db abstraction layer like pear::db or pear::mdb2).

with your own error handler you could then filter in the mysql errors like this
Code:
$result = @mysql_query("some query") or trigger_error("SQL-NONFATAL"); //for example
and then in your error handling function have a switch statement so that you can deal separately with fatal and non-fatal errors. you could also have a debug switch in your error handler so that different actions could be taken if you were debugging from those of a live environment. similarly you can differentiate between error handling actions for different classes of users.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top