Search code examples
phpsqlcodeigniteractiverecordwhere-in

How to write a parameterized WHERE IN (?) condition using CodeIgniter's query() method?


I wanto write a parameterized SELECT query in my CodeIgniter application.

I have an integer array with two values:

$prices = [23, 98];

I am trying to use that array in my IN condition, but the following attempt isn't working.

return $this->db->query(
    "select * from product where price IN (?)",
    array(implode(',',$prices)
)->result();

By checking $this->db->last_query(), this renders:

SELECT * FROM product WHERE price IN ('25,36')

Obviously, I don't want a single string value, but if I don't implode() the array in the parameter array, I get an error saying "operator does not exist".


Solution

  • Try this (untested)

    $query = $this->db->from('product')
                      ->where_in('price', implode(',',$prices))
                      ->get();
    

    The CodeIgniter Active Record docs are very good so you should definitely read up on it. For instance you'll notice the select() method is unecessary since we want all items so * is assumed.