Display user posts by category

Afternoon,

Looking for some direction with listing posts by category.

I started coding CMS (as a PHP beginner) and so far everything has been going well.

I made a link to the preset categories (category 1, category 2, etc.)

I also have a category table with category ID and name.

A table for user posts with CatID and category name in it, and

I am assuming that I will need to join tables to be able to list any posts in a specific category (select Cat 1 to see all Cat 1 posts. Same for Cat 2, 3, etc.)

When a user adds a post, it fills in the category name in the user records table, but I don't get the CAT ID and nothing is added to the category table, so how can I call this to display categorized posts?

I have a feeling that I'm probably thinking a lot about things and over-complicating things that should probably be easy to do.

The code I have at the moment (see below) has no effect?

Please help point me in the right direction, I've tried everything.

Thanks a lot everyone in advance

CODE:

$catSql ="SELECT        ID, Category
        FROM        categories
        LEFT JOIN   users_posts
        ON          CatID, category, BlogID";

$catQry = mysqli_query($link, $catSql);

while ($row = mysqli_fetch_assoc($catQry)){

    if($row['category_name'] != $lastCategory)
{
   $lastCategory = $row['category'];
   echo "<br /><strong>$lastCategory</strong>";
}        
echo $row['category'] . ' <br />';

}

      

+3


source to share


2 answers


Your SQL is wrong I think this should work



$catSql = "SELECT *
    FROM        categories
    LEFT JOIN   users_posts
    ON          categories.ID = users_posts.CatID";

      

+1


source


Your publish SQL records can check if the category ID exists in the url, and if so, use it to filter the results. Then you just need to create some links to the same page to add the required category id to the URL.

<a href='?cat=1'>Cat 1</a> | <a href='?cat=2'>Cat 2</a> | etc..

      



SQL

$sql = "SELECT * FROM POSTS";
if(isset($_GET['cat'])){
    $catID = (int)$_GET['cat']; //or something similar
    $sql .= " LEFT JOIN category USING categoryID WHERE categoryID = $catID";
}

      

+1


source







All Articles