Advertisement
Guest User

Untitled

a guest
Jun 11th, 2017
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.63 KB | None | 0 0
  1. // MySQL table:
  2. +----+--------+-------+
  3. | id | parent | name  |
  4. +----+--------+-------+
  5. |  1 |      0 | test  |
  6. |  2 |      0 | test1 |
  7. |  3 |      1 | test2 |
  8. |  4 |      1 | test3 |
  9. |  5 |      2 | test4 |
  10. |  6 |      0 | test5 |
  11. |  7 |      2 | test6 |
  12. |  8 |      3 | test7 |
  13. +----+--------+-------+
  14. 8 rows in set (0.00 sec)
  15.  
  16. // code
  17. <?php
  18. function getConnection()
  19. {
  20.     $user = 'user';
  21.     $host = 'localhost';
  22.     $password = 'pass';
  23.     $database = 'test';
  24.     $cn = mysql_connect($host,$user,$password);
  25.     mysql_select_db($database,$cn);
  26.     return $cn;
  27. }
  28.  
  29. function display_nodes($parent)
  30. {
  31.     $cn = getConnection();
  32.     $query = "SELECT a.id, a.parent, a.name FROM `menu` a WHERE parent = $parent";
  33.     $result = mysql_query($query,$cn);
  34.     echo "<ul>";
  35.     while($record = mysql_fetch_assoc($result))
  36.     {  
  37.         if(has_children($record['id']))
  38.         {  
  39.             echo "<li>{$record['name']}";
  40.             display_nodes($record['id']);
  41.             echo "</li>";
  42.         }  
  43.         else
  44.         {  
  45.             echo "<li>{$record['name']}</li>";  
  46.         }  
  47.     }  
  48.     echo "</ul>";
  49. }
  50.  
  51. function has_children($parent)
  52. {
  53.     $cn = getConnection();
  54.     $query = "SELECT COUNT(*) AS count FROM `menu` WHERE parent = {$parent}";
  55.     $result = mysql_query($query,$cn);
  56.     $record = mysql_fetch_assoc($result);
  57.        
  58.     if($record['count'])
  59.         return true;
  60.     else
  61.         return false;
  62. }
  63.  
  64. display_nodes(0);
  65.  
  66. // resutl:
  67.     * test
  68.           o test2
  69.                 + test7
  70.           o test3
  71.     * test1
  72.           o test4
  73.           o test6
  74.     * test5
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement