John Book John Book - 2 months ago 10
SQL Question

Sql select all the categories and for each category last 5 post

I have 2 table one categories and one posts .How do i select all the categories and last 5 post from each.

I have this code so far

include("includes/connect.php");
$get_cats = "select * from categories";
$run_cats = mysqli_query($con,$get_cats);

while ($cats_row=mysqli_fetch_array($run_cats)) {
$cat_id=$cats_row['cat_id'];
$cat_title=$cats_row['cat_title'];

echo '<div class="col-md-4 col-sm-6 col-xs-12">';
echo '<ul class="list-group ">';
echo '<li class="list-group-item table-header"><strong>';
echo $cat_title;
echo '</strong><span class="badge badge-color">12</span></li>';
echo '</ul>';
echo '</div>';

}


table structure categories

cat_id cat_title
1 sports
2 news
3 bla
4 bla


in post i have a categ_id

Answer

you can run your second query inside above while loop for getting category post data

while ($cats_row=mysqli_fetch_array($run_cats)) {
    $cat_id=$cats_row['cat_id'];

    $sql2="select * from post where cat_id=".$cat_id." order by id desc limit 5"; 
    $second2=mysql_query($sql2); 
    while (post_row=mysqli_fetch_array($second2)) {
        // do your stufff
    }
}
Comments