John Book John Book - 1 month ago 4x
SQL Question

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

$get_cats = "select * from categories";
$run_cats = mysqli_query($con,$get_cats);

while ($cats_row=mysqli_fetch_array($run_cats)) {

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>';

Structure of table categories

cat_id cat_title
1 sports
2 news
3 bla
4 bla

In post I have a categ_id.


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

while ($cats_row=mysqli_fetch_array($run_cats)) {

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