Error processing codeigniter database without num_rows ()

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.

+4
source share
2 answers

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

Alternatively, if you know the data is safe or you are ready to use $this->db->insert_string , you can add on duplicate key at the end of the request.

This should work (unverified):

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

I don't know if this works for $this->db->insert(); but $this->db->query(); will return false if these are errors so you can 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 } 
+2
source

All Articles