Hey guys i've been battling this problem for over a week now. and i still can't get it to work correctly.
I have a script that pulls out categores and sub categories from a mysql database. The output of this script looks similar to this:
Computers >> Software
Computers >> Software >> Games
Computers >> Software >> Programs
Computers >> Hardware
Computers >> Hardware >> Hard drives
Computers >> Hardware >> RAM
Computers >> Hardware >> Accessories
Now i want to pull this output into a <select> box drop down menu.
I can't seem to get it right. The script ends up timming out or showing one category repeatly around the page.
Here is the Original script: (displays on regular HTML doc)
<?php
function categories ($id, $depth) {
if ($id == 'NULL')
$query = "SELECT * FROM categories WHERE Parent IS NULL";
else
$query = "SELECT * FROM categories WHERE Parent = '" . $id . "'";
$result = mysql_query($query);
if (mysql_num_rows($result) < 1)
return;
while($row = mysql_fetch_array($result)) {
categories2 ($row, $depth);
}
}
//note that I had to split this into 2 functions
//because $depth will not restart on each loop
function categories2 ($row, $depth) {
echo($depth . $row['Name'] . "<br>");
$depth = $depth . $row['Name'] . " > ";
categories ($row['ID'], $depth);
}
// db data
$hostName = 'localhost';
$username = 'user';
$password = 'pass';
$databaseName = 'db';
//connect to DB
if(!($connection = @ mysql_pconnect($hostName, $username, $password)))
die("Could Not Connect to database");
if (!mysql_select_db($databaseName, $connection))
showerror();
categories("NULL", "");
Here's the script i've been work'n on: (display in a <select> box)
<?php
function categories ($id, $depth, $connection) {
if ($id == 'NULL')
$query = "SELECT * FROM categories WHERE Parent IS NULL";
else
$query = "SELECT * FROM categories WHERE Parent = '" . $id . "'";
$result = mysql_query($query);
if (mysql_num_rows($result) < 1)
return;
while($row = mysql_fetch_array($result)) {
categories2 ($row['ID'], $row['Name'], $depth, $query, $connection);
}
}
// Display the select
?><SELECT name="categories"><?
function categories2 ($cat_id, $cat_name, $depth, $query, $connection) {
if (($result = mysql_query ($query, $connection)))
{
while ($category = mysql_fetch_array($result))
{
?><option name="<?php echo $category['ID']; ?>"><?
echo($depth . $cat_name);
?></option><?
$depth = $depth . $cat_name . " > ";
categories ($category['ID'], $depth, $connection);
}
}else
echo "umm.. somthing messed up";
}
?></select><?
// db data
$hostName = 'localhost';
$username = 'user';
$password = 'pass';
$databaseName = 'db';
//connect to DB
if(!($connection = @ mysql_pconnect($hostName, $username, $password)))
die("Could Not Connect to database");
if (!mysql_select_db($databaseName, $connection))
showerror();
// run it
categories("NULL", "", $connection);
?>
If anyone could help me get this working right i really really would appreiciate it. Thank you!