I have a database table with the following data:
categoryId categoryName parentCategory
men Men root
women Women root
shoes Shoes root
mensshirts Men's Shirts men
menspants Men's Pants men
mensjeans Men's Jeans men
mensvests Men's Vests men
womensshirts Women's Shirts women
womenpants Women's Pants women
I’m using a recursive function to print out a tiered menu. The code is below.
function display_children($parent) {
global $connect;
$query = "SELECT categoryId, categoryName FROM categories WHERE parentCategory='$parent'";
$result = mysqli_query($connect,$query);
if ( $result === false ) {
printf("Query Error: %s\n", mysqli_error($connect));
exit();
}
echo "<ul>";
while ($row = mysqli_fetch_assoc($result)) {
extract($row);
echo "<li>".$categoryName."</li>";
display_children($categoryId);
}
echo "</ul>";
mysqli_close($connect);
}
display_children('root');
As a result, I get this printed out on screen:
- Men
- Men’s Shirts
- Men’s Pants
- Men’s Jeans
- Men’s Vests
- Women
- Shoes
The recursive function is not printing out the rest of the subcats, and I’m not sure why. My testing/debugging has confirmed that after mensvests is passed as a categoryId into the function, the next categoryId passed is women, which should locate the last subcats. Any ideas?
You are closing the DB connection at the end of the function. For recursive iterations, you will not have a connection to use after the first recursion goes to full depth.
A better approach would be to pass your db connection into the function as a parameter