Jump to content

php WHERE IN using arrays


chireficken

Recommended Posts

Hey all,I'm having a little difficulty with a php problem:I have an array,$dogs=[labs, collies, shepherds];I want to do a MySQL search usingSELECT * from dogs WHERE breed IN (labs, collies, shepherds); <-- this will obviously workMy dilemma is, is it possible to do something like:SELECT * from dogs WHERE breed IN ($dog[]); or SELECT * from dogs WHERE breed IN ($dog); <--this does notIs there some other way of doing this?Thanks,Nick

Link to comment
Share on other sites

Unfortunatly, that's not possible. The query must include all values.If you have a variable amount of array elements (which would be one reason you want to do something like this to begin with), you can always loop over the array, and construct the query as you go.BTW, the syntax in PHP for arrays is:

$dogs=array ('labs', 'collies', 'shepherds');

Link to comment
Share on other sites

If the values in the array have single quotes around them, you can use implode.

$dogs=array ("'labs'", "'collies'", "'shepherds'");$sql = 'SELECT * from dogs WHERE breed IN (' . implode(',', $dogs) . ')';

Link to comment
Share on other sites

If the values in the array have single quotes around them, you can use implode.
$dogs=array ("'labs'", "'collies'", "'shepherds'");$sql = 'SELECT * from dogs WHERE breed IN (' . implode(',', $dogs) . ')';

Yah its an array that collects info from a form, some of which fields wont be filled out. I may just fill the rest of the fields out with values that wont match anything using array_pad.I will also try the implode as well - Thanks for the suggestions!
Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...