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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.