簡體   English   中英

Code Igniter中沒有更新時,如何測試我的MySQL更新查詢是否成功?

[英]How do I test if my MySQL update query was successful when there is no update in Code Igniter?

我知道這是一個經常被問到的問題,但讓我解釋一下為什么我需要再次問這個問題。

大多數答案都建議使用

$this->db->affected_rows()

這在我的情況下不起作用,因為我可能遇到的情況是更新數據與數據庫中的數據相同,因此即使更新成功,它也會返回0。

我知道我可以編寫另一個查詢來檢查是否是因為數據相同,但這對我來說聽起來很愚蠢。

另一種方法是在代碼點火器中使用Active Record類,因此該行類似於:

$error_num = $this->db->update("users", array('firstName' => $newFirstName));
return $error_num;

這是一個更好的解決方案(至少即使重復數據導致沒有更新也可以使用)。 但是,我想使用數據庫類,例如:

$this->db->query('update table set field = somedata where id=1');

它提高了我的代碼對知道php + SQL但不熟悉代碼點火器的編碼器的可讀性,但是這就是為什么我要問是否有人知道以這種方式查詢如何得到錯誤號?

即在PHP中使用mysql_query($ query)時類似mysql_errno()的東西。

兩者將像相同的唯一區別

如果使用活動記錄類,則所有輸入變量都會自動轉義

如果您需要安全性,最好選擇主動記錄類

如果使用常規查詢執行,則必須使用$ this-> db-> escape_str()手動轉義輸入參數。

  $id = $this->db->escape_str($id)

您可以檢查查詢執行狀態。

$status =  $this->db->update("users", array('firstName' => $newFirstName));

if($status)
{
    //here you can check the number of affected rows if required
    echo $this->db->affected_rows();

}else{

      //here you can prcess for failure case
      log_message('Error', $this->db->_error_message());

}

//return the status to required place
return $status

我已使用此代碼進行檢查。

$status = $this->db->query('update table set field = somedata where id=1'); 
if($status)
   return true;
else
    return false;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM