Skip to content
Advertisement

CodeIgniter 3 not returning false in case of a DB query error

I have read as many related answers on SO related to this error I’m getting. However, NO question (or answer) is about CodeIgniter’s DB active query class returning FALSE when it SHOULD (since an error occurred). All it does is print the query error to the error log file in application/logs and exits.

The DB_DEBUG value is false.

$db['default']['db_debug'] = FALSE;

Here is the query being executed:

$this->db
    ->where('col_1_name', 'value')
    ->where_in('col_2_name', $array)
    ->delete('table_name');

The error occurs because $array is an empty array BUT that is not the problem – the problem is that it does not return false and just prints the query error to the error log file in applications/logs/. It is supposed to return false in case of an error, isn’t it? Otherwise how will anyone catch a database error?

After it writes that query’s error to the log file, it just exits the process. I’ve verified that by adding log_messages() before and after the above method.

Note: I’ve tried with DB_DEBUG = TRUE as well as FALSE and the same thing happens in both cases.

Note: CodeIgniter 3’s documentation says that the delete() method (as well as many other DB methods) return FALSE on failiure. https://www.codeigniter.com/userguide3/database/query_builder.html#CI_DB_query_builder::delete

Advertisement

Answer

Depending on how your site is set up, this is not an error. The method doesn’t magically return false when encountering a database error.

If db_debug is set to true, CI3 halts the execution upon encountering a database error, outputs the error to the screen and logs it, but you don’t get a chance to evaluate the error.

However, db_debug is set to false, you can check the value for $this->db->error() right after running the query and it’s there where you can check if the query ran OK or not.

I tried this with a select statement, but the behavior is exactly the same for delete, update, etc.

$query = $this->db->get();
log_message('debug', "Err: ".json_encode($this->db->error()));

This logs:

DEBUG - 2020-10-09 12:09:44 --> Err: {"code":0,"message":""}

when there is no error, and

 Err: {"code":1064,"message":"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 4"}

when there is an error.

$this->db->error() is actually an array, so instead of just logging it, you may check something like

$err = $this->db->error();
if ($err['code'] !== 0)
{
  // do something about the error or handle the excepcion
}

else
{
  // query ran OK, keep the method going
}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement