4

I'm having trouble finding a simple method for handling database errors in CI. For instance, I can't insert duplicate entries in my database table. If I try to, I get a 1062 database error.

The most common solution suggested is to check if the entry already exists and use

$query->num_rows() > 0

in a if-statement to prevent an error. That method seems redundant to me because I'm performing an extra query. Ideally I want to check if an error occurs in my main query or if a row is affected.

I found the following functions that may help

$this->db->affected_rows()

$this->db->_error_message()

however I'm not sure how to use them.

I tried in my Model:

$this->db->insert('subscription', $data);
return $this->db->affected_rows();

To my understanding that should return the number of effected rows. Then in my controller I added:

$affected = $this->Subscribe_model->subscribe($data);

if ($affected < 1)
{
    //display error message in view
}
else
{
   $this->Subscribe_model->subscribe($data); //perform query
}

Unfortunately the script stops in the model at $this->db->insert('subscription', $data); if an error occurs and displays the entire database error.

2 Answers 2

2

I do not know if this works for $this->db->insert();, but $this->db->query(); will return false if it errors so you could do something like this:

$sql = $this->db->insert_string('subscription', $data);
$sql = $this->db->query($sql)
if(!$sql){
    //Do your error handling here
} else {
    //query ran successfully
}
Sign up to request clarification or add additional context in comments.

Comments

1

Try using @$this->db->insert('subscription', $data);, @, in PHP means "suppress warning".

As an alternate -- if you know that data is safe, or you're willing to use $this->db->insert_string, you could add, on duplicate key to the end of the query.

This should work (untested):

$this->db->simple_query( $this->db->insert_string( 'subscription', $data ) . 
                            ' ON DUPLICATE KEY ' . 
                            $this->db->update_string( 
                                        'subscription', 
                                         $data, 
                                         /* your where clause here */ );

3 Comments

Thanks! Would IGNORE in the query also be a good solution? I'm trying to keep db queries minimal, should a duplicate row already exist.
Sure, I would just do str_replace( 'INSERT', 'INSERT IGNORE', $this->db->insert_string( 'subscription', $data ) );
You can also use query for this. simple_query, while useful for times when you want minimal processing, does not do as much as query does.

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.