1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

  2. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

PHP MySQL Loop on two-level data

Discussão em 'Outras Linguagens' iniciado por Stack, Julho 12, 2021.

  1. Stack

    Stack Membro Participativo

    I am trying to extract two layer data from mysql database with a single mysql query and then display it grouped by top-layer with a php while loop.

    <?php $org = "1";

    $row1 = mysqli_prepare($db,"SELECT * FROM menu WHERE org = ? ORDER BY mid DESC");
    $row1->bind_param("s", $org);
    mysqli_stmt_execute($row1); $row2 = mysqli_stmt_get_result($row1);

    while($row = mysqli_fetch_array($row2)){ ?>

    <div class="category"><?php echo $row["item"]; /* GROUPED*/?>
    <div class="item"><?php echo $row["item"]; /* INDIVIDUAL ITEM*/?></div>
    </div>

    <?php }; ?>

    mid parent org item price
    1 1 Category 1
    2 1 1 Item 1 $10
    3 1 1 Item 2 $12
    4 1 Category 2
    5 4 1 Item 3 $12
    6 4 1 Item 4 $90

    [​IMG]

    Obviously each item will appear only once but also the category will appear as many times as the underlying items. In the code however i need to group all items under the same parent category. Any ideas?

    Desired Result

    List
    Category 1
    - Item 1
    - Item 2
    Category 2
    - Item 3
    - Item 4

    Or in terms of the HTML code output:

    <div class="category">Parent Category 1<br>
    <div class="item">Item 1</div>
    <div class="item">Item 2</div>
    </div>
    <div class="category">Parent Category 3<br>
    <div class="item">Item 3</div>
    <div class="item">Item 4</div>
    </div>

    Continue reading...

Compartilhe esta Página