Bit of PHP/SQL help please?

Soldato
Joined
14 Apr 2003
Posts
4,950
Location
Deepest Yorkshire
Hi, I'm trying to select all rows from a database where a field on a row contains any of the characters in an array, is this possible?

for example $groups = "7 8 9"

I explode($groups, " ") to create an array

then try and get the right rows out the database with something like

$query = "SELECT * FROM quizes WHERE group LIKE '%$groups%'";

however firstly this doesn't work and secondly it only allows me to find 1 variable at a time

Any help greatly appreciated :)
 
Last edited:
Couldn't you use Count($arrayName) to count the number of entries in your array and then set up a loop based on this? On the first iteration you would supply the WHERE clause of your query and on subsequent iterations you would supply the AND's.
 
You should be able to use an IN construct rather than the LIKE (at least that's how DB2 does it)

Code:
SELECT * FROM quizes WHERE group IN (group1, group2, group3)
 
rpstewart said:
(at least that's how DB2 does it)

mySQL too—this is by far the best way :)

If you have to have them space separated, then:

Code:
$groups = mysql_real_escape_string(join(", ", explode(" ", $groups)));

$r = mysql_query("SELECT * FROM table WHERE group IN ($groups)");
 
Back
Top Bottom