简体   繁体   中英

Displaying Category and Subcategory in Tree Structure in PHP and MYSQLi

I am trying to display Category and Sub Category in Tree Structure as if I click on the Category then I can get multiple Subcategory associated with that Category.

I know this question asked multiple times but I found the answers unclear in all the questions asked previously.

I have created a table as:

category : cat_id  , catName
subcategory : id , cat_id , subCatName

I want to display all the category and when the user click on category then the subcategory should be listed. How can I do that?

<?php
  $db = new mysqli('localhost','user','password','dbname');
  $query = "SELECT id,cat FROM category";
  $result = $db->query($query);

  while($row = $result->fetch_assoc()){
    $categories[] = array("id" => $row['cat_id'], "val" => $row['cat']);
  }

  $query = "SELECT id, cat_id, subcat FROM subcategory";
  $result = $db->query($query);

  while($row = $result->fetch_assoc()){
    $subcategories[$row['cat_id']][] = array("id" => $row['id'], "val" => $row['subcat']);
  }

  $jsonCats = json_encode($categories);
  $jsonSubCats = json_encode($subcategories);


?>

<!docytpe html>
<html>

  <head>
    <script type='text/javascript'>
      <?php
        echo "var categories = $jsonCats; \n";
        echo "var subcategories = $jsonSubCats; \n";
      ?>
      function loadCategories(){
        var select = document.getElementById("categoriesSelect");
        select.onchange = updateSubCats;
        for(var i = 0; i < categories.length; i++){
          select.options[i] = new Option(categories[i].val,categories[i].id);          
        }
      }
      function updateSubCats(){
        var catSelect = this;
        var catid = this.value;
        var subcatSelect = document.getElementById("subcatsSelect");
        subcatSelect.options.length = 0; //delete all options if any present
        for(var i = 0; i < subcats[catid].length; i++){
          subcatSelect.options[i] = new Option(subcats[catid][i].val,subcategories[catid][i].id);
        }
      }
    </script>

  </head>

  <body onload='loadCategories()'>
    <select id='categoriesSelect'>
    </select>

    <select id='subcatsSelect'>
    </select>
  </body>
</html>

Is this what you are looking for? Doesn't do a tree structure, but you could easily change the dropdowns.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM