Jump to content

Looping from JOIN query


V

Recommended Posts

Sorry, I originally posted part of this in MYSQL Help, but I was advised to post it here. I'm hoping someone can help me out.

 

I have 2 tables. "categories" and "subcats" (sub categories). I used a JOIN query for both..

 

SELECT categories.*, subcats.* FROM categories JOIN subcats on (categories.cat_id = subcats.cat_id) ORDER BY cat_name

 

Then I used a while loop to echo all the categories from the "categories" table and their respective sub-categories from the "subcats" table.

 

$sql = "SELECT categories.*, subcats.* FROM categories JOIN subcats on (categories.cat_id = subcats.cat_id) ORDER BY cat_name";
$cats_result = $connection->query($sql) or die(mysqli_error($connection)); 

    while ($row = $cats_result->fetch_assoc()) { 
$cat_id = $row['cat_id'];
$cat_name = $row['cat_name'];
$subcat_name = $row['subcat_name'];

       //should output all categories once and nest their subcategories
echo "<strong>".$cat_name."</strong>"; 
echo "<br />";
echo $subcat_name; 
echo "<br />";

}

 

No MYSQL errors but unfortunately I get this output..

 

Technology

Computers

 

Technology

Gadgets

 

Technology

Robots

 

Health

Fitness

 

Health

Diet

 

What sort of code can use in the loop to echo categories just once instead of multiple times for each topic?

Link to comment
https://forums.phpfreaks.com/topic/209128-looping-from-join-query/
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.