How do I test if my MySQL update query was success

2020-05-30 03:46发布

I have a model function that updates a user in my CodeIgniter application:

// updates first of a user, return true if successful, false if not.
public function updateFirstName($userId, $newFirstName) {
    $this->db->query("UPDATE users SET firstName='$newFirstName' WHERE id=$userId");
    return // whether request was successful?
}

How do I return a boolean value that ensures the user of ID $userId has been updated? For instance, it should return false if no user was found with ID $userId.

10条回答
Luminary・发光体
2楼-- · 2020-05-30 04:14

You may use $this->db->affected_rows(); to check whether query runs successfully or not

查看更多
成全新的幸福
3楼-- · 2020-05-30 04:16

You can use $this->db->affected_rows() in Codeigniter this returns a numeric value when doing "write" type queries (insert, update, etc.).

In MySQL DELETE FROM TABLE returns 0 affected rows. The database class has a small hack that allows it to return the correct number of affected rows. By default this hack is enabled but it can be turned off in the database driver file. (From CI user guide). For deleted row in Ci it returns 1.

查看更多
小情绪 Triste *
4楼-- · 2020-05-30 04:18
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; 

EDIT

also(much better)

return ($this->db->affected_rows() > 0);
查看更多
来,给爷笑一个
5楼-- · 2020-05-30 04:25

Try this:

public function updateFirstName($userId, $newFirstName) {
    $this->db->where('id', $userId);
    $this->db->set('firstName', $newFirstName);
    $sql = $this->db->update('users');

    if ($sql) { return TRUE; }  // $sql - boolean true or false
}
查看更多
登录 后发表回答