Categories: Snippets

How do I test if my MySQL query was successful

if ($this->db->affected_rows() > 0)
{
  return TRUE;
}
else
{
  return FALSE;
}

or

if ($this->db->affected_rows() > 0)
  return TRUE;
else
  return FALSE;

or

return ($this->db->affected_rows() > 0) ? TRUE : FALSE;

also(much better)

return ($this->db->affected_rows() > 0);

A better solution I’ve found is to manage the difference between an ERROR and 0 affected rows. 0 affected rows is not necessarily a bad thing, but an error is something you do want to know about:

if ($this->db->_error_message()) {
    return FALSE; // Or do whatever you gotta do here to raise an error
} else {
    return $this->db->affected_rows();
}

Now your function can differentiate…

if ($result === FALSE) {
    $this->errors[] = 'ERROR: Did not update, some error occurred.';
} else if ($result == 0) {
    $this->oks[] = 'No error, but no rows were updated.';
} else {
    $this->oks[] = 'Updated the rows.';
}

Just some quick hacking there – you should obviously make the code far more verbose if you have other people using it.

The point is, consider using _error_message to differentiate between 0 updated rows and a real problem.

Recent Posts

Sample Contact Form with validation, Captcha & Notification

Contact Controller [crayon-68bdde9e93c69510560747/] Contact_form.php - view [crayon-68bdde9e93c79251690002/] Contact_model [crayon-68bdde9e93c80385141704/] Captcha Helper [crayon-68bdde9e93c89373677967/] Notifications_model [crayon-68bdde9e93c94864894151/] Database…

7 years ago

Delete Files and Execute Database Query remotely

[crayon-68bdde9e9409c119292025/] [crayon-68bdde9e940a3802429767/]  

7 years ago

Random String Codeigniter

[crayon-68bdde9e941e8002288217/] The first parameter specifies the type of string, the second parameter specifies the length.…

7 years ago

Codeigniter Ajax Form Validation Example

Create Controller [crayon-68bdde9e942c7111554312/] 2. Create View File [crayon-68bdde9e942cb396771452/]  

7 years ago

Codeigniter passing 2 arguments to callback – Email validation

[crayon-68bdde9e9440e946651541/] [crayon-68bdde9e94429470719803/]  

7 years ago

Setting Error Messages

All of the native error messages are located in the following language file: system/language/english/form_validation_lang.php To set…

7 years ago