Select multiple categories from the database

I am working on a blog system where blogs are classified and we can choose the category we want. To do this, I need to separate the blogs and categories tables. I know how to get blogs from all categories and from one category, but I don't know how to get blogs from several, but not all categories.

My code is as follows:

  <?php $query = ("SELECT blogs_id, title, body, posted_by, category FROM blogs INNER JOIN categories ON categories.category_id=blogs.category_id where category='cat1' ORDER BY blogs_id desc LIMIT 10"); $result = mysql_query($query) or die("error:".mysql_error()); while ($row = mysql_fetch_assoc($result)) { $title = $row['title']; $body = $row['body']; $posted_by = $row['posted_by']; ?> 

This code is designed to select one category, and it works well, but now I want to select several (but not all) categories. I tried several different options, but could not:

  <?php $query = ("SELECT blogs_id, title, body, posted_by, category FROM blogs INNER JOIN categories ON categories.category_id=blogs.category_id where category='cat1' AND category='cat2' AND category='cat3' ORDER BY blogs_id desc LIMIT 10"); 

This did not work.

+5
source share
3 answers

Use IN :

 WHERE category IN ('cat1', 'cat2', 'cat3') 

Alternatively, you can use OR :

 WHERE category = 'cat1' OR category = 'cat2' OR category = 'cat3' 
+4
source

Try OR instead of AND (in which condition). try the following:

 $query = ("SELECT blogs_id, title, body, posted_by, category FROM blogs INNER JOIN categories ON categories.category_id=blogs.category_id where category='cat1' OR category='cat2' OR category='cat3' ORDER BY blogs_id desc LIMIT 10"); 
+3
source

try it

 $query = ("SELECT blogs_id, title, body, posted_by, category FROM blogs INNER JOIN categories ON categories.category_id=blogs.category_id where category IN ('cat1', 'cat2', 'cat3') ORDER BY blogs_id desc LIMIT 10"); 
+1
source

All Articles