how to pass an array in sql statement ?

Discussion in 'Databases' started by hasanbasri, Dec 6, 2009.

  1. #1
    hello everybody

    I'm studying php and mysql and I want to use an array into where clause in sql qurey using this code

    
    $user[0]='admin';
    $user[1]='John';
    $user[2]='Sara';
    $user[3]='Muna';
    
    $sql="select * from table1 where 'name' IN $user";
    
    
    Code (markup):
    the last line always cause an error.
    I know the right way is to say :
    
    $sql="select * from table1 where 'name' IN ($user[0],$user[1],$user[2],$user[3])";
    
    
    Code (markup):
    but this method still not general and not flixable ;


    thank you
     
    hasanbasri, Dec 6, 2009 IP
  2. kingsoflegend

    kingsoflegend Well-Known Member

    Messages:
    202
    Likes Received:
    8
    Best Answers:
    0
    Trophy Points:
    108
    #2
    $arr=implode(",", $user);
    $sql="select * from table1 where 'name' IN ($arr)";
    Code (markup):
     
    kingsoflegend, Dec 6, 2009 IP
  3. hasanbasri

    hasanbasri Peon

    Messages:
    78
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #3
    :)
    WAW this is perfect , since where IN clause accept only comma seperated values .
    thanks
     
    hasanbasri, Dec 6, 2009 IP
  4. tukyunaaya

    tukyunaaya Peon

    Messages:
    14
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    thanx.. i was also looking for the same sort of solution.
    thanx a ton for replying.
     
    tukyunaaya, Dec 7, 2009 IP