tags:

views:

61

answers:

4

Is it possible to use an exception at the end of a mysql query instead of die()? I'd like to throw an exception and log it instead of killing the script.

Would it be done like:

mysql_query(...) or throw new exception()??
A: 

Yes. You can use an exception almost anywhere you'd traditionally use die/exit.

Alan Storm
Is my syntax correct up top?
Bebo
A: 

Yes, you can throw an exception instead of killing the script.

deamon
Thanks. I posted the syntax above but I don't think its correct
Bebo
+1  A: 

This is the way I normally do it. I have my database in a wrapper class, so $this simply refers to the wrapper.

private function throwException($query = null)
{
    $msg = mysql_error().".  Query was:\n\n".$query.
                   "\n\nError number: ".mysql_errno();
    throw new Exception($msg);
}

public function query($query_string)
{
    $this->queryId = mysql_query($query_string);
    if (! $this->queryId) {
        $this->throwException($query_string);
    }
    return $this->queryId;
}

That packages it all up with a nice error message for me, so I can see the problem query. You could keep it much simpler of course, and do:

mysql_query($sql) or throw new Exception("Problem with query: ".$sql);
zombat
Zombat, thanks. This will help me I think. I'd just like to be able to see the errors if and when they occur. I'm tired of banging my head on a wall only to find out later that my query was wrong.
Bebo
Yeah that should help then. An uncaught Exception will function almost the same as a `die()`, but you can get a little more information into and out of Exceptions.
zombat
It is bad design to use a property of the surrounding object if `queryId` is only used within this method. And by the way: it would be better (for security and performance) to use prepared statements.
deamon
A: 

Your given code would work fine:

mysql_query(...) or throw new Exception("Failed to run query");

But it's using shorthand that is not entirely clear. I personally think that you're better off sacrificing brevity for clarity:

if (false === mysql_query(...)) {
    throw new Exception("Failed to run query.");
}

Keep in mind that throwing Exceptions is only useful if you catch them somewhere, and in your case you probably want to use a custom exception:

class DatabaseException extends Exception {}

try {
    if (false === mysql_query(...)) {
        throw new DatabaseException("Failed to run query.");
    }
} catch (DatabaseException $e) {
    $logger->log("Database exception: " . $e->getMessage());
}

Hope that helps!

inxilpro
Actually, this does help me. What I think I can do is just add something in my database class for an exception. This is pretty straight forward though. Thank you for this.
Bebo