Advertisement
Guest User

Untitled

a guest
Mar 1st, 2019
185
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.71 KB | None | 0 0
  1. <?php
  2. $db_host = 'localhost';
  3. $db_user = 'root';
  4. $db_pass = '';
  5. $db_name = 'databasename';
  6. $conn = mysql_connect($db_host,$db_user,$db_pass) or die(mysql_error());
  7. mysql_select_db($db_name,$conn);
  8. mysql_query("SET NAMES 'utf8'");
  9. mysql_query('SET CHARACTER SET utf8');
  10. ?>
  11.  
  12. //connect to database
  13. $link = mysqli_connect('localhost','root','');
  14. mysqli_select_db($link,'databasename');
  15. //get all rows
  16. $query = mysqli_query($link,'SELECT * FROM categories');
  17. while ( $row = mysqli_fetch_assoc($query) )
  18. {
  19. $menu_array[$row['catid']] = array('catname' => $row['catname'],'parentid' => $row['parentid']);
  20. $menu_array[$row['catid']] = array('catname' => $row['catname'],'parentid' => $row['parentid'],'catid'=>$row['catid']);
  21. }
  22. //recursive function that prints categories as a nested html unorderd list
  23. function generate_menu($parent)
  24. {
  25. $has_childs = false;
  26. //this prevents printing 'ul' if we don't have subcategories for this category
  27. global $menu_array;
  28. //use global array variable instead of a local variable to lower stack memory requierment
  29. foreach($menu_array as $key => $value)
  30. {
  31. if ($value['parentid'] == $parent)
  32. {
  33. //if this is the first child print '<ul>'
  34. if ($has_childs === false)
  35. {
  36. //don't print '<ul>' multiple times
  37. $has_childs = true;
  38. echo '<ul>';
  39. }
  40. echo '<li><a href="category.php?catid='. $value['catid'] . '">' . $value['catname'] . '</a>';
  41.  
  42. while ( $row = mysqli_fetch_assoc($query) )
  43. {
  44. $menu_array[$row['catid']] = array('catname' => $row['catname'],'parentid' => $row['parentid']);
  45. }
  46.  
  47. $query = mysqli_query($link,'SELECT * FROM `categories`');
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement