Jump to content

[SOLVED] if (!$val) vs or die() -- Difference?? Benefits?? Any Guidance??


thepip3r

Recommended Posts

My question is, what are the differences (if any) of:

 

$q = mysql_query("SELECT COUNT(*) FROM quotes");
if (!$q) {
    errorHandler("mysql", 1);
}

 

vs.

 

$q = mysql_query("SELECT COUNT(*) FROM quotes") or die(errorHandler("mysql", 1));

 

Any clarification on best practices, etc would be greatly appreciated.

Yeah, the abrupt die() statements you see here on phpfreaks and elsewhere are really for debugging purposes.  When you are dealing with live applications, like Thorpe said, it better to deal with errors gracefully.  At the very least, displaying a full error page to the user as opposed to just exiting the script.

If you want to get fancy you should look into exception handling:

set_exception_handler('exception_handler');

$q = mysql_query("SELECT COUNT(*) FROM quotes");
if (!$q) {
    throw new Database_Exception('blah blah blah');
}

class Database_Exception extends Exception {
protected $message = 'Database Exception';
}

function exception_handler(Exception $e)  {
    //use this function to display a full error page
    echo $e->getMessage();
}

so... there's an implicit exit(); in die(); then?  i think that's what you guys are getting at and I do see the added value of letting the rest of your page load and just throwing a custom error.  thank you for the clarification.

 

@flyhoney - errorHandler() is my custom function that formats error messages certain ways, exits, and displays certain errors or not depending on whether i'm debugging or not.  currently, i'm using the if (!$val) structure so I didn't realize the implicit exit(); within die();

 

thanx again gents.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.