Pass a PHP array into Mysql 'IN' clause

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • bilibytes
    New Member
    • Jun 2008
    • 128

    Pass a PHP array into Mysql 'IN' clause

    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:

    Code:
    $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:

    Code:
    SELECT user_id
    FROM users
    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
    Recognized Expert Expert
    • Nov 2006
    • 5062

    #2
    Hi.

    You could try the implode function.

    For example:
    [code=php]
    <?php
    $array = array("first", "second", "third");
    $list = "'". implode("', '", $array) ."'";
    echo $list; // Outputs: 'first', 'second', 'third'
    ?>
    [/code]
    The $list string could then be used in the IN function.

    Comment

    • bilibytes
      New Member
      • Jun 2008
      • 128

      #3
      ok great, thankyou very much!

      bilibytes

      Comment

      • mohamedhafezqo
        New Member
        • Jan 2017
        • 1

        #4
        perfect, thanks very much

        Comment

        Working...