I am having trouble finding a simple method for handling database errors in CI. For example, I cannot insert duplicate records in a database table. If I try, I get a 1062 database error.
The most common solution is to check if the record exists and use
$query->num_rows() > 0
in the if statement to prevent an error. This method seems redundant to me because I am doing an additional request. Ideally, I want to check if an error occurs in my main request or if a string is affected.
I found the following features that might help
$this->db->affected_rows() $this->db->_error_message()
however, I am not sure how to use them.
I tried in my model:
$this->db->insert('subscription', $data); return $this->db->affected_rows();
In my understanding, that should return the number of rows produced. Then in the 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.
source share