Results 1 to 5 of 5

Thread: [RESOLVED] How to use for WHERE clause for an array?

  1. #1

    Thread Starter
    Fanatic Member
    Join Date
    Sep 2005
    Posts
    540

    Resolved [RESOLVED] How to use for WHERE clause for an array?

    In PHP you can do something like this:

    Code:
    $MySQL_Query = "SELECT * FROM `sometable` WHERE `columnname`='" . $somePHPVariable . "';";
    But how would you do the same thing for a PHP array (Keeping the code simple)?

    Here's an example of what I mean:
    Code:
    $somePHPArray['0'] = "Bob";
    $somePHPArray['1'] = "Jane";
    $somePHPArray['2'] = "Henry";
    $somePHPArray['3'] = "Amanda";
    $somePHPArray['4'] = "Joe";
    
    $MySQL_Query = "SELECT * FROM `sometable` WHERE `columnname`='" . $somePHPArray[?] . "';";
    What I mean by simple is not using a fancy loop to create multiple ORs inside the SQL query construction.

    Is what I'm asking for possible?

  2. #2
    Super Moderator si_the_geek's Avatar
    Join Date
    Jul 2002
    Location
    Bristol, UK
    Posts
    41,974

    Re: How to use for WHERE clause for an array?

    I don't know if PHP supports putting the array in, but in terms of SQL syntax it is better (shorter & generally more efficient) to use IN rather than multiple OR's, eg:
    Code:
    ... WHERE `columnname` IN ('Bob','Jane',Henry');

  3. #3

    Thread Starter
    Fanatic Member
    Join Date
    Sep 2005
    Posts
    540

    Re: How to use for WHERE clause for an array?

    I suppose I could use a for-loop and construct it using the IN way. It would be better then using multiple ORs.

    I'm going to bed, it's 2AM, lol. Will code it tomorrow unless someone has a better way when I check back.

    Thanks si_the_geek .

  4. #4
    WiggleWiggle dclamp's Avatar
    Join Date
    Aug 2006
    Posts
    3,527

    Re: How to use for WHERE clause for an array?

    Quote Originally Posted by si_the_geek
    I don't know if PHP supports putting the array in, but in terms of SQL syntax it is better (shorter & generally more efficient) to use IN rather than multiple OR's, eg:
    Code:
    ... WHERE `columnname` IN ('Bob','Jane',Henry');
    Thanks, you learn something new every day.
    My usual boring signature: Something

  5. #5
    I'm about to be a PowerPoster!
    Join Date
    Jan 2005
    Location
    Everywhere
    Posts
    13,647

    Re: How to use for WHERE clause for an array?

    One way:

    PHP Code:
    $names = array('Bob''Jane''T-Marts');
    function 
    clean_enquote_string($s) { return "'".mysql_real_escape_string($s)."'"; }
    $query 'select * from sometable where name in ('.join(','array_map("clean_enquote_string"$names)).')'

    There is some way of doing it with parameters, but I don't know it.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width