识别mysql的最佳方法是在php中的语句提取中更改“group by”字段值?

I have a sql query in my php:

$sql = "SELECT * FROM orderTaken WHERE orderStatus='10' GROUP BY orderId ORDER BY orderTakenTime DESC";

Now, I have to echo back several HTML tables based on different orderIds, so basically if the orderId is changed, a new HTML table will be created and contains the info of all the things under this orderId. This is what I have done(kinda pseudocode, please ignore the syntax error. My real code is far more complicated but the idea is here: set an oldOrderId and check it with the newly fetched orderId and see if the orderId is changed):

$sql = "SELECT * FROM orderTaken WHERE orderStatus='10' GROUP BY orderId ORDER BY orderTakenTime DESC";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$count = $stmt->rowCount();
for ($i = 0; $i<$count + 1; $i++ ){
    if ($row = $stmt->fetch()){
        $orderId = $row["orderId"];
        $2ndField = $row["2ndField"];
        $3rdField = $row["3rdField"];
        ...
        // check if $oldOrderId is set
        if (isset($oldOrderId)){
            // and compare, if the orderId changes, end the table and create a new one
            if ($oldOrderId != $orderId){
                echo "</table><br>";
                echo "<table><tr><th>...</th></tr>";
                ...
                //UPDATE old orderId
                $oldOrderId = $orderId;
            // if orderId doesn't change, continue echo table content
            } else {
                echo "<table><tr><td>...</td></tr>";
            }
        // if the oldOrderId is not set, it means this is the first fetched row, and the very first table will be created
        } else {
            echo "<table><tr><th>...</th></tr>";
            ...
            echo "<table><tr><td>...</td></tr>";
            ...
            //SET oldOrderId
            $oldOrderId = $orderId;
        }
    }
    if ($i == $count) {
        //End the last table
        echo "</table><br>";
    }
}

The code can run but will be buggy sometimes and I don't think this is a smart way to identify it. Is there any existed method like $row = $stmt->fetch().prev() to get the last row's orderId's value? Or if there's any better way to perform it?

Thanks!

The problem is your inclusion of GROUP BY orderId in your query. What this does is give you one row per each orderId in your table.

Since you are using SELECT *, then all you are getting back is one row for each orderId and one of the other values in the table for each of the other fields.

When using GROUP BY, you usually want to add a "group function" - like SUM(), COUNT(), GROUP_CONCAT(), etc. - to your query.

Your approach with the $oldOrderId is fine and could work if you change your query to something like:

SELECT * FROM orderTaken
WHERE orderStatus='10'
ORDER BY orderID DESC, orderTakenTime DESC