【问题标题】:Use multiple where condition in mysql在mysql中使用多个where条件
【发布时间】:2016-08-09 07:06:43
【问题描述】:

我有一个名为 categories[] 的选择字段,带有多项选择,我在更改功能上编写了一个,因此在更改功能上它将作为 id 数组进入控制器,现在我想要的是我想从 mysql 表中选择食物这些类别

<select name="categories[]">
    <?php 
      foreach ($category as $c) {

    ?>
     <option value="<?php echo $c->category_id; ?>"><?php echo $c->category_name;?></option>
    <?php
       }

     ?>
</select>

控制器

    public function get_foods(){

       $categories = $this->input->post(NULL,true);
       $sql = $this->subscription->get_foods($categories);
       $result = array(

                    'result' => $sql

       );
      echo json_encode($result);
    }

和模型

    public function get_foods($id){

    $sql = "SELECT * FROM food_category fc
            LEFT JOIN food f ON fc.food_id=f.food_id
            WHERE f.food_status = 1 AND
            fc.category_id = $id
            ORDER BY f.food_id DESC";
    $query = $this->db->query($sql);
    return $query->result_array();

}

我想获取这些类别中的所有食物,所以我认为我应该使用多个 where 条件?

【问题讨论】:

  • 这里有什么问题或疑问?请解释
  • 你应该发布的是get_foods()函数的代码。这就是我们所需要的。
  • 对不起@rmondesilva

标签: php mysql codeigniter where-clause codeigniter-3


【解决方案1】:

您只需要存储每种食物的类别,当您获得食物时,您可以使用 where 条件:

$this->db->where('category',$category);

【讨论】:

  • 如果 $category 是一个类别 id 的数组@PHP Geek,我可以使用这个
  • 不,这不是强制性的,因为 $category 是一个数组。它可能只是一个变量。
  • 不,我有一个数组,这就是我想使用多个 where@PHP Geek
  • 然后使用 $this->db->where($category);
【解决方案2】:

为此使用 () sql 函数中的 where 列。

关于它的详细描述。在这里找到 http://www.w3schools.com/sql/sql_in.asp

【讨论】:

    【解决方案3】:

    如果这有帮助,我认为您需要将类别一一发布,然后将其获取并放入一个数组中。这是一个可能有帮助的代码

    public function get_foods()
    {
        $result = array();
        foreach($this->input->post('categories') as $c)
        {
            $result[] = $this->subscription->get_foods($c);
        }
        echo json_encode($result);
    }
    

    对于模型,我建议使用 CI 的 AR

    public function get_foods($category)
    {
        $this->db->select('*');
        $this->db->from('food_category as fc');
        $this->db->join('food as f','fc.food_id = f.food_id','left');
        $this->db->where('f.food_status', '1');
        $this->db->where('fc.category_id',$category);        
        $query = $this->db->get();
        return $query->result_array();
    }
    

    首先我们创建一个空数组,然后使用 post 中的 foreach 获取每个类别的所有食物,然后将它们返回到结果数组中。

    希望这会有所帮助,如果 sql 中有任何错误,因为我可能忘记了一些连接,我愿意再次提供帮助。

    【讨论】:

      猜你喜欢
      • 2015-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-28
      • 1970-01-01
      • 2012-06-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多