1internet Posted August 29, 2013 Share Posted August 29, 2013 I want to list results that belong to a certain category. However, I have multiple categories and some results can belong to more than one cateogry. I want to a query that will show all the results from several categories, the number of categories will be aribitrary though. So I will have the categories contained within an array e.g. $cat_ids = array(12,26,32) And I want the query to be $sql = "SELECT * FROM `categories` WHERE `cat_id`=12 OR `cat_id`=26 OR `cat_id`=32"; Of course sometimes there may only be 1 category, and sometimes there could be 5. So how do you execute the array in the query? Or do I have to run a foreach loop? $sql = "SELECT * FROM `categories` WHERE" $i = 0; foreach ($cat_ids AS $cat_id){ if($i!=0) $sql = "OR " $sql = "`cat_id`=$cat_id" $i++ } Quote Link to comment https://forums.phpfreaks.com/topic/281653-array-in-query/ Share on other sites More sharing options...
mac_gyver Posted August 29, 2013 Share Posted August 29, 2013 mysql has an IN() comparison operator - $cat_ids = array(12,26,32); $ids = implode(',',$cat_ids); $sql = "SELECT * FROM `categories` WHERE `cat_id` IN($ids)"; Quote Link to comment https://forums.phpfreaks.com/topic/281653-array-in-query/#findComment-1447245 Share on other sites More sharing options...
Solution 1internet Posted August 29, 2013 Author Solution Share Posted August 29, 2013 Ah, thats what I thought! Thanks Quote Link to comment https://forums.phpfreaks.com/topic/281653-array-in-query/#findComment-1447246 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.