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"

.

.

.

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"; 
}

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.