Skip to content
Advertisement

How obtain a list of posts by category?

I have a MySQL table that associates articles with categories.

Table “posts_categories”:

On the page of article 170 “post.php? Id = 170”, I need to list all the posts in the same category. I need only show the post title. How do I make a list with all posts in category 4?

My SQL code is:

Advertisement

Answer

Your query has a couple of issues, firstly

should be

Secondly, to get all the posts in the same category as the input post, you need to change your WHERE condition to:

So your query should be:

Note that this query will leave you open to SQL injection (see this question). At the very least you should check that $id is a purely numeric value (you can use is_numeric), but ideally you should use prepared statements.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement