我的视图中有一个名为categories[]
的多选,其中包含表中id
的值。我想从categories[]
中获取值,并用它生成一个where子句:Where id = categories[] selected values
。但是,它是一个数组。如何使用数组值设置Where子句?所以我可以从categories[]
中获得id具有选定值的数据
我的表中有三列:
(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,
然后,我在控制器中得到这样的选择值:
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
}
最后,我在模型中设置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);
在你的第一个函数中,确保$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);
}
然后在您的模型中使用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-数据