4

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".

0

3 Answers 3

0

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I believe there is no need to implode the array $prices or else the entire array after implode will be considered as a single string. Simply passing the array seems to the syntax, as seen in the example in documentation.
Sorry John, this is my DV -- this answer is simply incorrect. This snippet will search for column values which match the solitary comma-separated string .
0

When executing a WHERE IN query() call with a placeholder, CodeIgniter does not expect the parentheses after IN. CodeIgniter will automagically wrap the IN values in parentheses. If you add your own paratheses, your SQL will break because of the double parenthetical wrapping.

The second parameter expects an array where each element relates to each placeholder in order. Pass your $prices array (unchanged) as the first/lone element of the parameters array.

return $this->db->query('SELECT * FROM product WHERE price IN ?', [$prices])->result();

You must not implode your array -- this will render an invalid SQL string with IN followed by the string value with no parentheses.


If you had two placeholders, it would be written like this:

return $this->db->query(
    'SELECT * FROM product WHERE active = ? AND price IN ?',
    [$active, $prices]
)->result();

To enjoy standardized quoting/escaping, use CodeIgniter's query building methods.

return $this->db->where_in('price', $prices)->get('product')->result();

Comments

-1

try this

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

1 Comment

This unexplained answer is simply incorrect. It makes no sense to call ->result() INSIDE of the unfinished query.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.