Connecting Tech Pros Worldwide Forums | Help | Site Map

Pass a PHP array into Mysql 'IN' clause

bilibytes's Avatar
Familiar Sight
 
Join Date: Jun 2008
Location: Europe
Posts: 128
#1: Nov 14 '08
Hi there,

is it possible to pass a PHP array to get some data matching in a Mysql Table?

lets say i have a list of names that i get from PHP into an array:

Expand|Select|Wrap|Line Numbers
  1. $php_array = array(0=>'john', 1=>'marcus', 2=>'robert', 3=>'samuel'...)
and i want to know which of these are in my Table.

could i do:

Expand|Select|Wrap|Line Numbers
  1. SELECT user_id
  2. FROM users
  3. WHERE user_name IN ($php_array)
i don't know if mysql can make it..

is there a way to perform this?


thank you,

best regards

Atli's Avatar
Moderator
 
Join Date: Nov 2006
Location: Iceland
Posts: 3,753
#2: Nov 14 '08

re: Pass a PHP array into Mysql 'IN' clause


Hi.

You could try the implode function.

For example:
Expand|Select|Wrap|Line Numbers
  1. <?php
  2. $array = array("first", "second", "third");
  3. $list = "'". implode("', '", $array) ."'";
  4. echo $list; // Outputs: 'first', 'second', 'third'
  5. ?>
  6.  
The $list string could then be used in the IN function.
bilibytes's Avatar
Familiar Sight
 
Join Date: Jun 2008
Location: Europe
Posts: 128
#3: Nov 18 '08

re: Pass a PHP array into Mysql 'IN' clause


ok great, thankyou very much!

bilibytes
Reply


Similar MySQL Database bytes