Dynadot โ€” .com Registration $8.99

PHP/MySQL Query

Spaceship Spaceship
Watch

Ik

Quality //VIP Member
Impact
8
Hi experts :)

I have the following MySQL table - PAGES:
Code:
id_page
id_parent
title

What I need to do is to write a query or a script that displays a site map as the following:

Home
About Us
-- Our Mission
-- Our Team
---- Managers
---- Technical Team
-- Our Location
Contact Us


Please note that the depth is unlimited.

Thanks
 
0
•••
The views expressed on this page by users and staff are their own, not those of NamePros.
GoDaddyGoDaddy
Hi,

You need to use a technique called "recursion" for this.

What this means is that you have a function that calls itself. We start examining the table for root entries ("Home", "About Us", "Contact Us" in your example. I have assumed these have a id_parent of -1). We then display that name, then call the function again to search for entries that have the same id_parent as our current id_page.

Something like this (untested):

PHP:
<?php

function menu($parent = -1, $level = 0)
{
    $res = mysql_query("SELECT * FROM table WHERE id_parent='$parent'");

    while ($item = mysql_fetch_object($res))
    {
        echo str_repeat("--", $level).$item->title."<br />\n";
        // Recurse
        menu($item->id_page, $level+1);
    }
}

?>

You must be careful with recursion that you don't get stuck in an endless loop. If you do, PHP will continue recursing until it runs out of stack space and core dumps.
 
0
•••
Excellent. Thanks a lot
 
0
•••
Thank u so much for your sharing its really informative for me.
 
0
•••
I would call the function within an increment limited loop just to be safe, kind of like a timeout, but instead of time, it timouts when you loop X number of times.
 
0
•••
Dynadot โ€” .com Registration $8.99Dynadot โ€” .com Registration $8.99
Appraise.net
Unstoppable Domains
Domain Recover
DomainEasy โ€” Live Options
  • The sidebar remains visible by scrolling at a speed relative to the pageโ€™s height.
Back