[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?
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');
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 :).
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');
:wave: Thanks, you learn something new every day.
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.