-2

I have a dynamic array. For example like this.

$color = array('red','blue','green');
"SELECT * FROM mytable where colors=(red or blue or green)"

But my array is dynamic. So I don't know the values and how can I loop the array and select the rows.

halfer
  • 19,824
  • 17
  • 99
  • 186
athi
  • 123
  • 9
  • use a loop and iterate over the array and fetch results. – Lal May 07 '16 at 11:00
  • 3
    http://stackoverflow.com/questions/920353/can-i-bind-an-array-to-an-in-condition – Chris May 07 '16 at 11:02
  • Use `IN` in mysql, add the number of placeholders you need and bind the variables. **Edit:** Exactly like in the question @Chris mentions... – jeroen May 07 '16 at 11:03

2 Answers2

1

try this

<?php

 $color = array('red','blue','green');


 $ss = 'SELECT * FROM mytable where colors IN ("' . implode('", "', $color ) . '")';

output :

SELECT * FROM mytable where colors IN ("red", "blue", "green")

?>
JYoThI
  • 11,977
  • 1
  • 11
  • 26
  • Not sure this would work jothi since the in () expects string values to be wrapped in single quotes. – Jeff May 07 '16 at 12:03
  • if i select red, it is selecting the rows whose color=red but if i select red and blue, it is returning empty result.. i need something like "SELECT * FROM mytable where colors = RED OR BLUE OR GREEN – athi May 07 '16 at 16:06
  • IN method working fine for what you expected result .i think something missing in your array @athi – JYoThI May 09 '16 at 04:33
  • try to echo $ss the query and know that query building working fine or not @athi – JYoThI May 09 '16 at 04:33
0

use where in.

SELECT * FROM your_table WHERE  COLUMN IN $your_dynamic_array
Abhishek
  • 3,900
  • 21
  • 42