Codeigniter handle database error without num_rows()
I'm having trouble finding a simple method for handling database errors in CI. Fo开发者_JAVA百科r 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.
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
}
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 */ );
精彩评论