-6

Possible Duplicate:
MySQL query using an array
How to use an array of values from PHP in the 'IN' clause of mysql query?

from a Post form i have an array like that

Array
(
    [userid] => Array
        (
            [0] => 4e8329e97231c
            [1] => 4e64b47849318
            [2] => 4e4e415a30000
        )

)

i am little struggle to retrieve the users data from mysql from this array

that should be something like this :

SELECT * FROM user_detail WHERE user_id='4e64b47849318' OR user_id='4e8329e97231c' OR user_id='4e4e415a30000'
Community
  • 1
  • 1
user505790
  • 21
  • 6

6 Answers6

7

Use implode().

$yourArray = array_map("mysql_real_escape_string", $yourArray);

$query = "SELECT * FROM user_detail WHERE user_id='";
$query .= implode($yourArray, "' OR user_id='");
$query .= "'";

Or indeed, use the SQL IN keyword:

$yourArray = array_map("mysql_real_escape_string", $yourArray);

$query = "SELECT * FROM user_detail WHERE user_id IN ('";
$query .= implode($yourArray, "','");
$query .= "')";
CodeCaster
  • 147,647
  • 23
  • 218
  • 272
2
$clean_userid = array_map('mysql_real_escape_string', $arr['userid'])
$str_user_id = "'" . implode("', '", $clean_userid ) . "'";
$sql = "SELECT * FROM user_detail WHERE user_id IN ( $str_user_id )"; 
ariefbayu
  • 21,849
  • 12
  • 71
  • 92
  • 1
    It would probably be good practice to use `array_map('mysql_real_escape_string', $arr['userid'])` instead of `$arr['userid']`. –  Nov 16 '11 at 21:50
1

You can use the MySQL IN operator nicely here, it works like "OR" but you can essentially give it a list.

$user_id_string = implode(',', $array['userid']);

You now have a comma separated string of your user_id's.

Now query something like:

SELECT * FROM user_detail WHERE user_id IN ($user_id_string);
DJSunny
  • 1,970
  • 3
  • 19
  • 27
1

$criteria = "'".implode("','",$userID)."'";

$sql = "select * from user_detail where user_id in ($criteria)";

Ben Guthrie
  • 959
  • 2
  • 8
  • 17
1

You could try

"SELECT * FROM user_detail
WHERE user_id IN ('". implode("','", $array['userid'])."')"
Marco
  • 56,740
  • 14
  • 129
  • 152
  • ALL answers were downvoted by some spammer, it's nothing personal with your code I guess :P – Esailija Nov 16 '11 at 16:04
  • All answers except CodeCaster's. Odd, that. But as for this answer, you're not quoting your IDs. – cHao Nov 16 '11 at 16:09
  • 1
    @cHao: CodeCaster's was the only answer not offering a blatant SQL injection vulnerability. – Boann Nov 16 '11 at 16:16
  • @Boann: Ooo...there is that. Heh...i'm usually the one bitching about those. Dunno why i missed it. – cHao Nov 16 '11 at 16:19
1
$query="SELECT * FROM user_detail 
           WHERE user_id='".(intval) $array['userid'][0]."' 
           OR user_id='".(intval) $array['userid'][1]."'  
           OR user_id='".(intval) $array['userid'][2]."'"; 
Sudhir Bastakoti
  • 99,167
  • 15
  • 158
  • 162