2017-04-06 121 views
1

我使用Codeigniter 3,PHP和MySQL。Codeigniter選擇和(條件)更新查詢

我想從MySQL數據庫中選擇一條記錄,並根據結果運行更新查詢。

If result = 0, update. 
If result = 1, do nothing. 

我的代碼到目前爲止是;

public function addData($itemId) { 
    $gDescription = 'test'; 
    $gPreviewLink = 'test'; 
    $gThumbnail = 'test'; 
    $gPageCount = 'test'; 

    $this->db->select('g_data'); 
    $this->db->from('item'); 
    $this->db->where('item_id', $itemId); 
    $query = $this->db->get(); 
    $result = $query->result(); 
    // var_dump($result) returns array(1) { [0]=> object(stdClass)#22 (1) { ["g_data"]=> string(1) "0" } } 

     $data = array(
     'item_description' => $gDescription, 
     'item_preview_link' => $gPreviewLink, 
     'item_thumbnail' => $gThumbnail, 
     'item_pageCount' => $gPageCount, 
     'g_data'   => '1', 
     'g_data_timestamp' => 'NOW()' 
     ); 
     // if result = 0 update 
     if($result == '0') { 
     $this->db->where('item_id',$itemId); 
     $this->db->update('item', $data); 
    } 
     } 

是否有任何原因數據不會在我的數據庫中更新?我沒有收到任何錯誤消息。

任何幫助,將不勝感激。

+0

實際上你還沒有在這裏問過問題...... –

+0

是$結果數字還是字符?頂部的例子顯示數字,但你==爲一個字符'0' – xQbert

回答

1

$query->result()返回一個對象數組,其中每個對象都是表中的一行。 (你可以在後續代碼var_dump看到您的意見)

沒有其他改變你的條件應該是

if($result->g_data == '0') { ... 

這就是說,你應該早在數據庫atually返回結果的方法進行檢查。此外,你不需要多行如果你做到以上所以不要用result()使用「行()」,而不是

... 
$query = $this->db->get(); 
// The following will set $result to the value of "g_data" if there 
// are rows and to "0" if there are none. 
$result = $query->num_rows() > 0 ? $query->row()->g_data: '0'; 
... 

那麼條件可以保持你擁有它編碼

if($result == '0') {...