2

Possible Duplicate:
I have an array of integers, how do I use each one in a mysql query (in php)?

I am trying to create some filtering function and I would like to know if it is possible, within a mysqli query, to check if the table row has a value equal to just one of those in the array. I hope the code will make it clearer:

$age=array(37,35);
$query = mysqli_query($link, "SELECT * FROM users WHERE age = $age");

So I want the query to return all the rows of users whose age is either 37 or 35, but the above code doesn't work.

Using

...WHERE age = 35 OR age = 37"

Won't do, because I want it to be dynamic so to speak.

Thanks

Community
  • 1
  • 1
Patrick
  • 89
  • 7

5 Answers5

4

Use SQL's IN() clause.

SQL Example:

SELECT * FROM users WHERE age IN (35, 37)

PHP Example:

$query = "SELECT * FROM users WHERE age IN (" . implode(',', array_map('intval', $age)) . ")";

Note: Be mindful of SQL Injection.

Jason McCreary
  • 71,546
  • 23
  • 135
  • 174
2
$age=array(37,35); 
$age_str=implode(',',$age);
$query = mysqli_query($link, "SELECT * FROM users WHERE age in ($age_str)"); 
amaksr
  • 7,555
  • 2
  • 16
  • 17
1

Use the php join method together with an IN clause in the SQL

$age=array(37,35);
$query = mysqli_query($link, "SELECT * FROM users WHERE age IN (".join(",", $age).")");
Richard Harrison
  • 19,247
  • 4
  • 40
  • 67
1

Use it like this:

$query = mysqli_query($link, "SELECT * FROM users WHERE age IN (" . implode(",",$age) . ")");
hjpotter92
  • 78,589
  • 36
  • 144
  • 183
1

Use in clause.

$ageArr = implode(',',$age);
SELECT * FROM users WHERE age IN ($ageArr);
Nishu Tayal
  • 20,106
  • 8
  • 49
  • 101