Club multiple data from the database and display them together

I have a table structure that looks like this: here the orderid will be generated randomly.

id  orderid  product  Cost  userid
1     1       P1       C1    1
2     1       P2       C2    1
3     1       P3       C3    1
4     2       P4       C2    1
5     2       P5       C1    1
6     3       P2       C2    2
7     3       P3       C3    2
8     4       P4       C2    3
9     4       P5       C1    3

      

I want to combine this data according to the orderid (according to the user id) and then display this data as a table where products that have the same order should be displayed together.

it is like a shopping cart in which I place multiple items in the cart and when I confirm the order (all products together) a unique order will be created for that order. and now i want to display products for this order and under each order i want to display all products

the view should look something like this (according to the user id)

enter image description here

the code i am currently using to display data,

 <?php
    $sql = "SELECT * FROM cart where userid='".$userid."'";
    $result = mysqli_query($con, $sql);
    if (mysqli_num_rows($result) > 0) 
        {
            while($row=mysqli_fetch_assoc($result))
                {
                    /*
                    *
                    code for displaying tabular data
                    *
                    */
                }
        }
    ?>

      

The problem is, I can't put them together

+3


source to share


2 answers


Use ORDER BY



 <?php
    $sql = "SELECT * FROM cart where userid='".$userid."' ORDER BY orderid asc, id asc";
    $result = mysqli_query($con, $sql);
    if (mysqli_num_rows($result) > 0) 
        {
            while($row=mysqli_fetch_assoc($result))
                {
                    /*
                    *
                    code for displaying tabular data
                    *
                    */
                }
        }
    ?>

      

0


source


Try this if it solves your problem. But I have no raw data to test on

<?php
    $sql = "SELECT * FROM cart where userid='".$userid."'";
    $result = mysqli_query($con, $sql);
    $test=NULL /// first store data in a single array.
    if (mysqli_num_rows($result) > 0) 
    {
        while($row=mysqli_fetch_assoc($result))
        {
            $test[$row['orderid']][]=$row;
        }
    }
    //Now we have stored all data in $test  

    // test output. please add gui as u need 
    foreach($test as $orderid => $products)
    {
        echo'<br/>OrderID: '.$orderid;
        foreach($products as $p)
        {
            echo'<br/>Product: '.$p['product'].' Cost:'.$p['cost'];
        }
    }
    ?>

      



The good thing about this implementation is that all data is retrieved in an array so that it can be returned as a whole.

0


source







All Articles