selecting multiple categories from database

I am working on a blog system where blogs are categorized and we can choose the category we want to. For this, I have to separate the tables blogs and categories. I know how to get blogs from all categories and from a single category, but I don’t know how to get blogs from multiple but not all categories.

My code looks like this:

Read More
 <?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 for selecting a single category and it works well, but now I want to choose multiple (but not all) categories. I tried a few different options, but failed:

 <?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 didn’t work.

Related posts

3 comments

  1. Use the IN clause:

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

    Alternatively, you can use OR:

    WHERE category = 'cat1'
       OR category = 'cat2'
       OR category = 'cat3'
    
  2. Try OR in place of AND (in where condition). try this:

    $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. Try this

    $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");
    

Comments are closed.