Legend1989 Legend1989 - 2 months ago 6
MySQL Question

Count rows in a SQL group

I have a script that I want to put on a dashboard. The SQL works and groups the items in the while and it is displayed in the dashboard correctly. However I also want the QTY's to show.

So if the SQL is grouping how can I count the rows it returns so I can echo the QTY out in to my table for each row. This is my code.

<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "dbname";
$custid = $row['CustomerID'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql1 = "SELECT * FROM stock
JOIN hardware ON stock.HardwareID = hardware.HardwareID
WHERE stock.CustomerID = $custid GROUP BY stock.HardwareID";
$result1 = $conn->query($sql1);
if ($result1->num_rows > 0) {
// output data of each row
while($row1 = $result1->fetch_assoc()) {
echo "<tr>";
echo "<td>".$row1['Hardware']."</td>";
echo "<td></td>";
echo "</tr>";
}
}
?>


So the aim is to have the row

echo "<td></td>";


Have a variable in it that shows the qty for each row that is grouped.

Answer

you can use this query, group by query has to select and provide aggregation, here i have provided count, if you require some of appropriate column you can change it accordingly...

            <?php
                $servername = "localhost";
                $username = "root";
                $password = "root";
                $dbname = "dbname";

                $custid = $row['CustomerID'];

                // Create connection
                $conn = new mysqli($servername, $username, $password, $dbname);
                // Check connection
                if ($conn->connect_error) {
                    die("Connection failed: " . $conn->connect_error);
                } 
                $sql1 = "SELECT stock.Hardwareid, count(*) as CountHardware FROM stock 
                JOIN hardware ON stock.HardwareID = hardware.HardwareID
                WHERE stock.CustomerID = $custid GROUP BY stock.HardwareID";
                    $result1 = $conn->query($sql1);

                if ($result1->num_rows > 0) {
                    // output data of each row
                    while($row1 = $result1->fetch_assoc()) {
                        echo "<tr>";
                        echo "<td>".$row1['Hardware']."</td>";
                        echo "<td></td>";
                        echo "</tr>";
                    }
                }
            ?>
Comments