Search code examples
phpsqlcodeigniterquery-builderwhere-in

CodeIgniter SELECT query WHERE column equals a value and another column has a value found in a whitelist


I have content that i want to filter by a brandname and a permission id and then show it.

my problem is: When i send one value as $permission it works fine. But when a user has multiple permission_id's it doesn't work.

WHERE `permission_id` = 1, 2, 3;

I have a problem with my select query:

$this->db->select('*');
$this->db->from('content');
$this->db->where('brand_name', $brand);
$this->db->where('permission_id', $permission);

SQL:

SELECT *
FROM `content`
WHERE `brand_name` = $brand_name
    AND `permission_id` = $permission;

The print_r of $brand & $permission look like this:

Hyundai
1,10,11,2,3,4,5,6,7,8,9

Solution

  • To test a field against multiple values, your SQL should not look like :

    WHERE permission_id = 1, 2, 3;
    

    I don't know what your permission_id field looks like, but I guess your condition should rather be:

    WHERE permission_id IN (1, 2, 3);
    

    Try with where_in:

    $this->db->where_in('permission_id', $permission);
    

    where $permission is an array containing the permissions (not a comma separated string).

    With $permission being a string, use explode:

    $this->db->where_in('permission_id', explode(',', $permission));