2016-12-15 94 views
2

當我嘗試這種代碼:笨更新多行的where子句

$query = ''; 
foreach ($data as $row) 
{ 
    $where = array(
       'community_id' => $row->id, 
       'user_id'  => $this->session->user_id, 
       'status'  => 'invited_to_join', 
      ); 
    $update = array(
       'status' => 'joined', 
      ); 
    $query .= $this->db->set($update)->where($where)->get_compiled_update('community_members').'; '; 
} 
if ($query) 
{ 
    return $this->db->query($query); 
} 

它給我的錯誤:

You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'UPDATE community_members SET status = 'joined' WHERE community_id = '18' A' at line 4

this answer使用簡單的查詢使用CASE,但我不知道如何將其轉換爲Codeigniter的查詢生成器。

回答

3

試試這個例子;

您可以直接在這裏像這樣使用數組$data['id'],無需循環使用作爲我的冠癭

 $this->db->set('status','joined'); 
     $this->db->where('community_id',$data['id']); 
     $this->db->where('user_id',$this->session->user_id); 
     $this->db->where('status','invited_to_join'); 
     $this->db->update('community_members'); 
+0

謝謝!我知道它必須非常簡單..我想知道爲什麼我看不到第二個和第三個子句可以像這樣加入.. – dapidmini

+0

當然,您可以使用加入where子句.... @ dapidmini –

+0

$ where =「'community_id'=」。$ data ['id']。「AND user_id =」。$ this-> session-> user_id。「AND status ='invited_to_join'」; $ this-> db-> where($ where); –

2

您還可以使用where條款是這樣的:

$where = "'community_id'=".$data['id']." AND user_id=".$this->session-user_id." AND status='invited_to_join'"; 

    $this->db->set('status','joined'); 
    $this->db->where($where); 
    $this->db->update('community_members'); 

謝謝!

+0

我認爲你的第一個答案要好得多。此方法需要手動字符串轉義.. – dapidmini