Aamer
Aamer

Reputation: 775

Getting categories from database to HTML Optgroups and options in php

I am trying to get my categories from the database with their subcategories into <optgroup> and <option> tags and I want the parents to be <optgroup> tags but I can't loop through all the levels, I only get to level 2 and I can't get too far!

This is what I got so far:

$con = mysql_connect($dbHost, $dbUsername, $dbPassword);
if (!$con) {
    echo "Cannot connect to the database: " . mysql_error();
    exit;
}

$db_selected = mysql_select_db($dbName, $con);
if (!$db_selected) {
    echo "Can\'t use $dbName : " . mysql_error();
    exit;
}

$query = "SELECT * FROM categories";

$result = mysql_query($query);
$pidHolder = null; // To take the current parent pid in the loop
$optOpen = false;  // Check that optgroup tag is opened
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
    if ($line['parent_id'] == 0 && $line['cat_id'] == 0)
        continue;
    if ($line['parent_id'] == 0) {
        if ($optOpen) {
            echo '</optgroup>';
            $optOpen = false;
        }
        echo "<optgroup value=" . $line['cat_name'] . "\" label=\"" . $line['cat_name'] . "\">";
        $pidHolder = $line['cat_id'];
        $optOpen = true;
        continue;
    } else if (isset($pidHolder) && $pidHolder == $line['parent_id']) {
        echo '<option value="' . $line['cat_id'] . '">' . $line['cat_name'] . '</option>\n';
        continue;
    }
}
mysql_close();

What's the problem with my code? and what do I need to loop through the rest of children?

Upvotes: 2

Views: 763

Answers (1)

Hussein Alkahli
Hussein Alkahli

Reputation: 21

try to use a recursive function in order to easily manage your categories and putting them in a <optgroup> and <option>.

Upvotes: 1

Related Questions