![](/img/trans.png)
[英]how to select data with multiple select value as where clause ? - Ajax Codeigniter
[英]How to select data with array value on where clause with ajax - codeigniter
我的視圖中有一個名為categories[]
的多個 select ,其中包含我表上的id
值。 我想從該categories[]
中獲取值並使用它創建一個 where 子句: Where id = categories[] selected values
。 但是,它是一個數組。 如何使用數組值設置 Where 子句? 所以我可以從categories[]
中獲取 id 具有所選值的數據
我的表中有 3 列:
(id, category, name)
。
我的表的值是:
(1, "food", "Pizza")
(2, "food", "Burger")
(3, "drink", "Mineral Water")
(4, "drink", "Tea")
(5, "snack", "Apple Pie")
我所做的是:通過在我的視圖中執行此命令來獲取選定的值:
var v = $('[name="categories[]"]').val();
//and doing like this, so I can get it to my controller
"data": 'cat=' + v,
然后,我得到 controller 中的選定值,如下所示:
public function getData(){
$cat = $this->input->post('cat');
$where = array('id' => [$cat]);
$result = $this->my_model->getData($where);
//and some code to set the data in my table
//and code for return the data
}
最后,我在 model 中設置 WHERE 子句,如下所示:
public function getData($where){
$this->db->select('*');
$this->db->from($this->table);
$this->db->where($where);
$query = $this->db->get();
return $query->resut();
}
我在上面完成的方式如下產生查詢:
Unknown column 'Array' in 'where clause'
SELECT `id`, `category`, `name` FROM `my_table` WHERE `id`= Array ORDER BY `category` ASC
您需要的 SQL 是WHERE IN
,查詢看起來像這樣
SELECT * FROM table WHERE id IN (12,14,55,346);
在您的第一個 function 中,確保 $cat 是一個數組
public function getData(){
$cat = $this->input->post('cat');
if (!is_array($cat)) $cat = explode(",", $cat);
$where = array('id' => $cat);
$result = $this->my_model->getData($where);
}
然后在 model 中使用 where_in()
public function getData($where){
$this->db->select('*');
$this->db->from($this->table);
$this->db->where_in($where);
$query = $this->db->get();
return $query->result();
}
https://codeigniter.com/userguide3/database/query_builder.html#selecting-data
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.