简体   繁体   中英

select products from specific category codeigniter

Products are available in following categories

product_id   category_id
     2            1,2
     3            1,3
     4            1,13
     2            2,5

I want to select products of specific category eg all products from category 2. what will be sql syntax

You can use FIND_IN_SET for seach in comma separated values.

 $this->db->where("FIND_IN_SET( '$category_id' , category_ids) "); 

So your whole query be like

$this->db->select();
$this->db->from('table_name');
$this->db->where("FIND_IN_SET( '$category_id' , category_ids) "); 
$query = $this->db->get();
return $query->result();

You can try this FIND_IN_SET for search comma separated values.

    <?php
    $this->db->select();
    $this->db->from('table_name'); 
    $this->db->where(' FIND_IN_SET(category_ids, "' . $category_ids . '") > 0', NULL, false);
    $query = $this->db->get();
    return $query->result();
    ?>

I hope it will help.

You can use a simple SQL query & use this in your model.

public function get_product_category($category_id)
{
     $query = "SELECT * FROM product_table WHERE category_id LIKE '%$categoryid%'";
     return $this->db->query($query, $category_id)->result();
}

It will find in your product table where category_id contain example 2 .

But, like M Khalid Junaid said, you better learn about database normalization.

For example : Normalization Table

This is your table before normalized, the product ID is duplicated on 2 how can if that is a primary key ? So, try to change your table to normalized table, it will help you so much.

product_id   category_id
     2            1,2
     3            1,3
     4            1,13
     2            2,5

This is a new table are normalized after creating a table named group_table or whatever. Then set group_id as a primary_key

group_id       product_id       category_id
    1               2                 1
    2               2                 2
    3               3                 1
    4               3                 3        
    5               4                 1
    6               4                 13
    7               2                 5

The query for find the product from category_id is more simple, just

SELECT * FROM group_table WHERE category_id = $category_id

or any condition that you wanted to create. Like if you wanted to get product name just JOIN the table from product_table

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