Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have created an array in php containing a few USER_IDs. I am using mysql database having a table named USERS. Now I want to select only those rows from USERS whose user_id is matched with USER_IDs in the array.

Thanks in advance

share|improve this question

3 Answers

 $ids = join(',',$user_ids);  
 $sql = "SELECT * FROM USERS WHERE user_id IN ($ids)";

PHP/MYSQL using an array in WHERE clause
http://www.php.net/manual/en/function.join.php
http://www.php.net/manual/en/function.implode.php

share|improve this answer
To all other @users, please do not provide duplicate answer. – Imran Naqvi Sep 24 '11 at 13:08
+1, to the point answer. – Imran Naqvi Sep 24 '11 at 13:09

implode() the array into an IN clause in your SQL:

$sql = "SELECT * FROM tbl WHERE USER_ID IN (" . implode(",", $user_ids) . ");";

This assumes your user ids are integers, rather than strings which must be quoted and escaped. In that case,

$sqlids = array();
foreach ($user_ids as $id) {
  // Escape and quote each id
  $sqlids[] = "'" . mysql_real_escape_string($id) . "'";
}
$sql = "SELECT * FROM tbl WHERE USER_ID IN (" . implode(",", $sqlids) . ");";
share|improve this answer
3  
Downvoter care to comment? – Michael Berkowski Sep 24 '11 at 12:41
1  
Maybe it's someone who thinks they need to upvote the answer they like and downvote the others (mine too)? – Jared Farrish Sep 24 '11 at 12:54
@JaredFarrish Odd. you got my +1. If it was my question I'd accept yours too. – Michael Berkowski Sep 24 '11 at 12:57
pity, we cant see who voted down... – Marek Sebera Sep 24 '11 at 12:58

The IN examples above are perhaps cleaner, but this is another approach. I have put in formatting for human readability. Note, be sure and use mysql_real_escape_string() when building the $users array if the user names are user-submitted or otherwise potentially not safe.

<?php

$users = array('jim','mary','bob');

$userids = "USER_ID = '".implode("' \n   OR USER_ID = '",$users)."'";

echo "
SELECT *
FROM USERS
WHERE $userids
";

?>

OUTPUTS

SELECT *
FROM USERS
WHERE USER_ID = 'jim' 
   OR USER_ID = 'mary' 
   OR USER_ID = 'bob'

http://codepad.org/YfkPBEaJ

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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