PHP/MySQL Query

SpaceshipSpaceship
Namecheap AuctionsNamecheap Auctions
Namecheap AuctionsNamecheap Auctions
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
Close
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
Close
Excellent. Thanks a lot
 
0
Close
Thank u so much for your sharing its really informative for me.
 
0
Close
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
Close
AIVikingsAIVikings

We're social

Escrow.com
Spaceship
Domain Recover
CryptoExchange.com

NamePros updates

New: watch any domain
You can now watch domains on NamePros. We check each one and notify you when something changes. Search for a domain and press Watch on...
AIVikings
Catchy
  • The sidebar remains visible by scrolling at a speed relative to the page’s height.
Back