-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
  • 139,522
  • 20
  • 204
  • 252
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,241
  • 12
  • 69
  • 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,930
  • 1
  • 19
  • 27
1

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

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

Ben Guthrie
  • 909
  • 2
  • 7
  • 17
1

You could try

"SELECT * FROM user_detail
WHERE user_id IN ('". implode("','", $array['userid'])."')"
Marco
  • 55,302
  • 13
  • 128
  • 150
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
  • 97,363
  • 15
  • 155
  • 158