Home » Php » php – Loop through one table with another loop for each record

php – Loop through one table with another loop for each record

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have one table with categories and another table with linkrecords for each category and the table structure looks like this:

categories:

id (int)
name (varchar)

links:

id (int)
link (varchar)
fk_cat_id (int)

Here is how I do now, but know that it is a no go with a query within a query:

$query = "SELECT * FROM categories";
if ($result = $mysqli->query($query)) {
    while ($row = $result->fetch_assoc()) { 
        $catid = $row['cat_id'];

        echo 'CatName: '.$row['name'];
        echo '<ul>';

        $query2 = "SELECT * FROM links WHERE fk_cat_id = $catid";
        if ($result2 = $mysqli->query($query2)) {
            while ($row2 = $result2->fetch_assoc()) { 
                echo '<li>'.$row2['link'].'</li>';
            }
        }

        echo '</ul>';

    }
}

I guess I have to go to some JOIN method, but not sure how!

How to&Answers:

Following query will be used to retrieve links with relation to link categories.
Also, It is a good practice to specify fields name in query to retrieve specific columns only instead of *.

SELECT links.id AS link_id, links.link, links.fk_cat_id, categories.name
FROM links
JOIN categories ON categories.id = links.fk_cat_id;