Jump to content

displaying links depending on ID from another table


xox

Recommended Posts

I have two tables categories and subcategories and what I want do is display them but here I ran into problem displaying the subcategories. Here's the code that doesn't work, all it does it displays categories.

$query = "SELECT ID,name FROM `categores`";
        $result = mysql_query($query) or die(mysql_error());
       
        while($row = mysql_fetch_array($result))
        {
        echo $row['name'];
        $id_main=$row['ID'];
        $query2 ="SELECT name_subcategory FROM subcategories WHERE id_main_category=".$row['ID'];
        $result2 = mysql_query($query2) or die(mysql_error());
        while ($row2=mysql_fetch_array($result2));
        {       
            echo $row2['name_subcategory']; 
        }
        echo "<br />";
        }

 

Display should be

-category

--subcategory

--subcategory

-another category

--subcategory of "another category"

.

.

.

Link to comment
Share on other sites

Learn how to do JOINS - never run queries in a loop - it is a huge performance hit on the server. Below is a much better approach, but I don't know why your code wasn't showing the sub categories. Most likely, the data is not properly "linked" in the database.

 

$query = "SELECT c.ID, c.name, sc.name_subcategory
          FROM `categores` AS c
          JOIN `subcategories` AS sc ON sc.id_main_category = c.ID";
$result = mysql_query($query) or die(mysql_error());

//Flag to determine change in category
$currentCatID = false;
//Process the records
while($row = mysql_fetch_array($result))
{
    //Test if this is a new category from the previous
    if($currentCatID != $row['ID'])
    {
        //Display the category name and set flag
        echo "<br /><b>{$row['name']}</b><br />\n";
        $currentCatID = $row['ID'];
    }
    //Display the subcategory
    echo "{$row['name_subcategory']}<br />\n"; 
}

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.