Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // MySQL table:
- +----+--------+-------+
- | id | parent | name |
- +----+--------+-------+
- | 1 | 0 | test |
- | 2 | 0 | test1 |
- | 3 | 1 | test2 |
- | 4 | 1 | test3 |
- | 5 | 2 | test4 |
- | 6 | 0 | test5 |
- | 7 | 2 | test6 |
- | 8 | 3 | test7 |
- +----+--------+-------+
- 8 rows in set (0.00 sec)
- // code
- <?php
- function getConnection()
- {
- $user = 'user';
- $host = 'localhost';
- $password = 'pass';
- $database = 'test';
- $cn = mysql_connect($host,$user,$password);
- mysql_select_db($database,$cn);
- return $cn;
- }
- function display_nodes($parent)
- {
- $cn = getConnection();
- $query = "SELECT a.id, a.parent, a.name FROM `menu` a WHERE parent = $parent";
- $result = mysql_query($query,$cn);
- echo "<ul>";
- while($record = mysql_fetch_assoc($result))
- {
- if(has_children($record['id']))
- {
- echo "<li>{$record['name']}";
- display_nodes($record['id']);
- echo "</li>";
- }
- else
- {
- echo "<li>{$record['name']}</li>";
- }
- }
- echo "</ul>";
- }
- function has_children($parent)
- {
- $cn = getConnection();
- $query = "SELECT COUNT(*) AS count FROM `menu` WHERE parent = {$parent}";
- $result = mysql_query($query,$cn);
- $record = mysql_fetch_assoc($result);
- if($record['count'])
- return true;
- else
- return false;
- }
- display_nodes(0);
- // resutl:
- * test
- o test2
- + test7
- o test3
- * test1
- o test4
- o test6
- * test5
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement