This question already has an answer here:

I have an array called $restaurantArray which contains a selection of restaurant id's.

Is there anyway I can execute a mysql query that will return rows if their id is equal to one of these restaurant ID's in the array?

Thanks.

share|improve this question

marked as duplicate by Tim Cooper, Daedalus, hjpotter92, raven, Tim Bish Apr 20 '13 at 15:42

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1  
Have you tried anything yet? If so, please show that, as well as how you're interacting with the database. – Daedalus Apr 19 '13 at 20:20
    
This might be useful: stackoverflow.com/a/11181663/1208233 – Yang Apr 19 '13 at 20:59
up vote 1 down vote accepted

You can use IN with your mysql query. Just implode the array $restaurantArray into the string, using comma as a delimiter; cover this string with brackets; and use the result string as input to the query. Something like

// uncomment if data needs to be sanitized
// $restaurantArray = array_map("mysql_real_escape_string", $restaurantArray);
$input = '(' . implode(',', $restaurantArray) . ')';
$query = "SELECT from foo WHERE id IN $input";
share|improve this answer
2  
Vulnerable to injection attacks.. – Daedalus Apr 19 '13 at 20:28
    
How is it vulnerable to such attacks if the array comes directly from the database! – sark9012 Apr 19 '13 at 20:32
    
Use this snippet before the DB query. foreach($restaurantArray as $key=>$value) { $restaurantArray[$key] = mysql_real_escape_string($value); } – Ankesh Apr 19 '13 at 20:33
1  
You can never assume these things. Everything must be escaped. Period. – tadman Apr 19 '13 at 20:34
1  
You'd use $query = "SELECT from foo WHERE id IN $input ORDER BY RAND() LIMIT 3"; – Connor Gurney Apr 19 '13 at 22:28

Not the answer you're looking for? Browse other questions tagged or ask your own question.