2017-07-03 112 views
0

我正在基於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; 
+0

如何確定「更新查詢已成功執行」? – urfusion

+0

會不會是這種情況?如果該值與數據庫中的值相同,則不會更新,因此您需要更改修改的時間以使其正常工作 – Exprator

+0

@urfusion我在數據庫中有一個使用ON UPDATE CURRENT_TIMESTAMP的時間字段。所以,時間正在更新。 –

回答

0

您可以使用transaction檢查如果查詢成功執行或不。之後,您可以檢查$ 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; 
+0

我喜歡你顯示的消息「用戶編輯成功,但它看起來像你的避難所沒有更新任何東西!「。讓我檢查解決方案。 –

+0

您的答案奏效!非常感謝。 –

+0

@ChrisMurphy不客氣。 –

0

它將返回numeric價值,而不是true請檢查使用 if($this->db->affected_rows() > 0) 請閱讀文檔here

+0

爲ref:https://stackoverflow.com/questions/16909257/check-number-of-affected-rows-in-codeigniter –

0

按照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 
     ); 
    } 

} 
+0

克里斯墨菲,你可以做一件事,直到用戶沒有改變任何值,不啓用更新按鈕。 –

相關問題