tags:

views:

43

answers:

5

Simple question I guess, I want to use PHP to write an update to an existing row in my database, if it doesn't happen I want to log the failure but continue executing the code. While it would be nice to have records of failures to track down issues, that the update failed isn't that important to my user, nor will it affect the running of any other code; the query is simply for a 'cosmetic' but entirely unnecessary piece of information.

My database class's query function is set to die on failure, could I modify that or is there another way of doing it without altering my standard query code?

A: 

Well, I would just take out the die(). That, alone, will keep it from stopping all CGI execution. If you somehow want to log failures, why not add a function that writes to a log file, or maybe sends you an e-mail with the failure (if you're not talking about a high fail rate, and just want to debug).

dclowd9901
+1  A: 
if(mysql_query($sql)){
  // Database command succeeds
}
else{
  // Database command fails
}
Brendan Long
+2  A: 

This is what exceptions are good at.

Tiny example using mysql

class Db
{
  function query( $sql )
  {
    $result = @mysql_query( $sql );
    $error = mysql_error();
    if ( !empty( $error ) )
    {
      throw new DbException( $error );
    }
    return $result;
  }
}

class DbException extends Exception{}

And then

try {
  $db = new Db;
  $db->query( 'select * from table' );
}
catch ( DbException $e )
{
  // do nothing - we want silent failure
}
Peter Bailey
so, what's the difference with just $db->query( 'select * from table'); without try catch if we want silent failure? ;)
Col. Shrapnel
The point is to not have Db::query *always* fail silently - just when you want it to. Also, there's more flexibility - the calling script can log the error or take some other action.
Peter Bailey
+1  A: 

get rid of die() then?

Id' suggest to use trigger_error() instead of die. You will be notified of error via standard error output.

Col. Shrapnel
A: 

I would implement a method that logs/mails the error. Your end users won't notice anything at all.

$query = mysql_query($sql) or log_error($sql);

// continue executing code

function log_error($sql) {
  // Code that writes to a log file

  // Notify tech support 
  mail("[email protected]", "Error while updating DB", $sql . " at time: " . time());
}
Kris Van den Bergh
Consider trigger_error() using instead of log_error, as it's way more flexible, and great advantage in developing phase
Col. Shrapnel