简体   繁体   中英

Use multiple where condition in mysql

i have a select field named categories[] with multiple select and i written one on change function so on change fuction it will go the controller as an array of id's now what i want is i want to select foods from mysql table with these categories

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

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

     ?>
</select>

controller

    public function get_foods(){

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

                    'result' => $sql

       );
      echo json_encode($result);
    }

and model

    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();

}

i want to fetch all the foods in these categories, so i think i should have to use some multiple where condition ?

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

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

use the where columns in () sql function for this.

for detail description on it. find here http://www.w3schools.com/sql/sql_in.asp

If this can help, I think you need to post the categories one by one, then get it and put it in one array. Here is a code that may help

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

and for the model I suggest making use of AR of CI

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();
}

First we make an empty array, then using the foreach in post we get all the foods per category then return them inside the result array.

Hope this helps and if there's any error in the sql since I may have forgotten some of the join, I'd be willing to help again.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM