Welcome Guest, Not a member yet? Register   Sign In
Handling Database Errors
#1

[eluser]Wonder Woman[/eluser]
Hi,

I was just wondering what the best way to deal with database errors is? I have seen on some scripts that they end their functions with "return false;" - is this common practice? I was just wondering what the best way to go about dealing with the odd exception of a script not running successfully because it could not find the id in the database for example.

Any advice would be great, thanks.
#2

[eluser]Cristian Gilè[/eluser]
Hi WW,

Quote:I was just wondering what the best way to deal with database errors is? I have seen on some scripts that they end their functions with “return false;” - is this common practice?

It's a common practice but not the best. For example:

If you perform an update on db with a where condition but the condition is not satisfied the query return TRUE even if the affected rows are zero. So when doing "write" type queries (insert, update, etc.) use $this->db->affected_rows() after query has been executed.

In production, db debug mode, should be disabled so use a try catch statement to trap errors. For example:

in your model:

Code:
if( $this->db->insert('tabel_name', $data) != TRUE)
      {
        throw new Exception('i can not insert');
      }
      else
      {
        return $this->db->affected_rows();
      }

in your controller:

Code:
try
{
      $affected_rows = $this->your_model_name->db_insert();
      } catch (Exception $e) {
        echo 'Caught exception: ',  $e->getMessage(), "\n";
}

Cristian Gilè




Theme © iAndrew 2016 - Forum software by © MyBB