1

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? 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
    }
}

1 Answer 1

2

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;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.