i hoping to create a recursive function which i don\'t have an idea yet
this is my code to fetch category from database
Something like this?
function getCategories($mid, $categoryParent = 1)
{
$return = '';
$results = mysql_query("SELECT * FROM categories WHERE category_parent = '$categoryParent' ORDER BY lft ASC", $mid);
while($row = mysql_fetch_array($results)) {
$return .= "<li><a href='/{$row['category_safe_name']}/'>{$row['category_name']}</a></li>";
$subs = getCategories($mid, $row['category_id']);
if (!empty($subs)) {
$return .= '<ul>';
$return .= $subs;
$return .= '<ul>';
}
}
return $return;
}
$mid = mysql_connect($host, $user, $pass);
echo getCategories($mid);
Would print out all your categories, of course fix it to exactly how you want, but that should give you an idea of how recursive functions could work
What you need to do, is build a recursive function. That is, a function that calls itself within. An example:
function getCategories($parent=0) {
$res = mysql_query("SELECT * FROM categories WHERE category_parent = '$id' ORDER BY left ASC");
if (mysql_num_rows($res) > 0) {
$category = mysql_fetch_object();
echo '<ul>';
echo '<li><a href="' . $category->category_safe_name . '">' . $category->category_name . '</a>';
getCategories($category->category_id);
echo '</li>';
}
}
If I've made any typos in regards to table and column names then obviously swap them out for the correct values.
You should have a look at Managing Hierarchical Data in MySQL.
It gives a good overview of some approaches to using hierarchical data in MySQL.
I would do :
<?php
function getChildren($id=1) {
$sql = mysql_query("SELECT * FROM categories WHERE category_parent = '$id' ORDER BY lft ASC");
echo "<ul>";
while($row = mysql_fetch_array($sql)) {
echo "<li><a href='/{$row['category_safe_name']}/'>{$row['category_name']}</a>";
getChildren($row['category_id']);
echo "</li>";
}
echo "</ul>";
}
getChildren();
?>