我有一个脚本,我想放在仪表板上。 SQL在while中对项目进行工作和分组,并在仪表板中正确显示。但是我也希望QTY显示出来。
因此,如果SQL正在分组,我如何计算它返回的行数,这样我就可以将QTY回显到每一行的表格中。这是我的代码。
<?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>";
}
}
?>
所以目的是拥有行
echo "<td></td>";
在其中有一个变量,显示分组的每一行的数量。
答案 0 :(得分:2)
你可以使用这个查询,逐个查询必须选择并提供聚合,这里我提供了计数,如果你需要一些合适的列,你可以相应地改变它...
<?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>";
}
}
?>