[英]Where clause match to variable not working
美好的一天! 我有這個查詢:
$name = $this->input->get_post('name');
$unit = $this->input->get_post('unit');
$user = $this->session->userdata('user');
$sql = $this->db->query("select ID from type WHERE code LIKE '%".$unit."%'");
$result = mysql_query($sql);
$this->db->set('Name', $name);
$this->db->set('Unit', $result);
$this->db->set('Owner', $user);
$this->db->set('CreatedBy', $user);
$this->db->set('ModifiedBy', $user);
$this->db->insert('prod');
$this->db->select('ID');
$this->db->from('type');
$this->db->where('%'.$unit.'% = type.code');
$id = $this->db->insert_id();
return (isset($id)) ? $id : FALSE;
我不知道為什么在where子句中有條件時,為什么不能用表type
的ID
值設置表Unit
。
有人能幫我嗎?
我不確定代碼試圖完成什么,但是like()
不需要包含%。 如果調用like('type.code', '%1234%')
,查詢將具有WHERE type.code LIKE '%\\%1234\\%%'
。 所以你可以只寫$this->db->like('type.code', $unit);
如果您只希望%放在一側或想要明確,% like()
可以使用第三個參數,可以是'both'
, 'before'
, 'after'
或'none'
來指定在哪里插入%。
那可能不是你唯一的錯誤:
$sql = $this->db->query("select ID from type WHERE code LIKE '%".$unit."%'");
$result = mysql_query($sql);
文檔說上述代碼中的$sql
將是一個結果對象,對其調用mysql_query()
將產生不可預測的結果。 要獲取實際的結果對象,應該調用$sql->result()
(如果您希望獲得多於一行)或僅調用$sql->row()
因為似乎只在查找一行。
$this->db->set('Unit', $result);
在這里,您要使用$result->ID
(假設$result
是行而不是行數組)。 將單位設置為$result
不會起作用。 要么將Unit設置為0,要么根據$result
是stdClass
對象而不是標量值的事實設置其他一些無意的值。
希望能有所幫助。
重命名“類型”表,如code_type,然后查看它是否有效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.