Search code examples
phpsqlcodeignitererror-handlingcodeigniter-3

codeigniter 3 query error handling


I'm in the process of migrating a CI2 project to CI3.

One thing I am having difficulties with is handling errors on db queries. Could someone please tell me the correct way to do this as I cannot seem to find the answer in the docs or previous SO questions.

Basically, if the query results in a sql error i want to return false. At the moment it seems that error() returns an array and so is always returning true regardless of whether there is an error or not meaning my method always returns false.

function get_post()
{
    $post = //some db call to get a post

    if ( $this->db->error() )
    {
        return false;
    }
    else
    {
        return $post
    }
}

Solution

  • Handling Errors

    $this->db->error();
    

    If you need to get the last error that has occurred, the error() method will return an array containing its code and message.

    Here’s a quick example:

    if ( ! $this->db->simple_query('SELECT `example_field` FROM `example_table`')) {
        $error = $this->db->error(); // Has keys 'code' and 'message'
    }
    

    1 : Changes in config/database.php

    'db_debug' => FALSE,
    

    2:

    function get_post() {
    
        $post = //some db call to get a post
    
        $error = $this->db->error();
    
        if ( ! empty($error['code'])) {
            return FALSE;
        } else {
            return $post;
        }
    }