[英]Codeigniter - update query executed successfully but $this->db->affected_rows() returns false
我正在基於Codeigniter
的Web項目上工作,我需要從管理面板更新用戶。 如果更新的值與數據庫中已存在的值不同,則它可以正常工作。 問題是$this->db->affected_rows()
如果值不同,則返回TRUE
,但如果值相同,則返回FALSE。
這是我的代碼:-
// $where contains the array for where clause
// $data contains the array of user's data which includes the updated value
$this->db
->where($where)
->update('users', $data);
if($this->db->affected_rows() == true)
{
$response = array(
'message' => "User edited successfully",
'status' => true
);
}
else
{
// this else block always get executed if the updated value is equal to the value already exists in database. But in reality the record was updated successfully
$response = array(
'message' => "Unable to edit user",
'status' => false
);
}
return $response;
它將返回numeric
值,不是true
請使用if($this->db->affected_rows() > 0)
請在此處閱讀文檔
您可以使用事務檢查查詢是否成功執行。 之后,您可以檢查$ this-> db-> affected_rows()來查看管理員是否真的更新了用戶值,並相應地返回了消息。
更新的代碼:
$this->db->trans_start();
// $where contains the array for where clause
// $data contains the array of user's data which includes the updated value
$this->db
->where($where)
->update('users', $data);
$this->db->trans_complete();
if($this->db->trans_status() === FALSE)
{
$response = array(
'message' => "Unable to edit user",
'status' => false
);
}
else
{
if($this->db->affected_rows() > 0)
{
$response = array(
'message' => "User edited successfully",
'status' => true
);
}
else
{
$response = array(
'message' => "User edited successfully, but it looks like you haven't updated anything!",
'status' => true
);
}
}
return $response;
根據CI文檔, $this->db->affected_rows()
如果用戶進行了任何編輯,則返回true;如果查詢成功執行但用戶未更改數據,則返回false。
您只需確認查詢已成功運行。如果查詢成功運行,則意味着您的數據已更新。
$result = $this->db
->where($where)
->update('users', $data);
if ( ! $result)
{
// Error
}else{
// Function ran ok - do whatever
if($this->db->affected_rows() == true)
{
$response = array(
'message' => "User edited successfully",
'status' => true
);
} else {
$response = array(
'message' => "There is nothing to update",
'status' => false
);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.