1

I have two tables; One is category and the other one is sub_category.

First I want to display all the items in category and store the value of each category and then display all the sub_categories related to that category but the category should not repeat (it should be displayed only once for all sub-categories).

.this is the output

<?php 
    $abcd = $mysqli->query("SELECT * FROM categories;");
    while($obj = $abcd->fetch_object())
    {
        $category = $obj->name;
        $results = $mysqli->query("SELECT * FROM `sub-category` WHERE category = '$category';");
        while($omg=$results->fetch_object())
        {
            echo $category. ' '.$omg->subcategory.'<br>';
        }
        echo $omg->subcategory;
    }
?>
11
  • change your categories query to something like SELECT * FROM DISTINCT categories Commented Jan 5, 2017 at 17:36
  • and learn some sql, it is very powerful skill to write great software, and it is very easy learn w3schools.com/sql/default.asp Commented Jan 5, 2017 at 17:37
  • @xFighter That will not work. Trivially, there can be multiple subcategories for each category. The categories relation already contains unique categories. Commented Jan 5, 2017 at 17:37
  • $abcd, $obj, $omg ... Variable naming 101 Commented Jan 5, 2017 at 17:38
  • 1
    @xFighter That seems like reasonable output. Perhaps displayed like a tree. Moving the print of the (parent) category out of the inner loop would address that. Using a single SQL query would be an even bigger improvement - and teach additional concepts the OP may not be familiar with. Commented Jan 5, 2017 at 17:46

2 Answers 2

1

Create an array of subcats and implode them so you only get commas where you want them. Only print the $category outside the loop.

<?php 
    $abcd = $mysqli->query("SELECT * FROM categories ");
    while ($obj = $abcd->fetch_object()) {                   
      $category = $obj->name;
      $results = $mysqli->query("SELECT * FROM `sub-category` WHERE category = '$category' ");     

       echo $category.': ';

       $subcats = array();
       while ($omg = $results->fetch_object()) {
         $subcats[] = $omg->subcategory;
       }

       echo implode(',', $subcats).'<br>';
    }
?>
Sign up to request clarification or add additional context in comments.

Comments

0

Use a simple JOIN.

<?php 
    $abcd = $mysqli->query('SELECT DISTINCT categories.name,sub-category.subcategory FROM `categories` JOIN `sub-category` ON category.name = categories.category;');
    while($obj = $abcd->fetch_object())
    {
        echo $obj->name.' '.$obj->subcategory.'<br>';
    }
?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.