gpt4 book ai didi

php - 计算 SQL 组中的行数

转载 作者:行者123 更新时间:2023-11-29 07:10:43 25 4
gpt4 key购买 nike

我有一个脚本想要放在仪表板上。 SQL 工作并对项目进行分组,并正确显示在仪表板中。不过,我还希望显示数量。

因此,如果 SQL 正在分组,我如何计算它返回的行数,以便我可以将每行的数量回显到表中。这是我的代码。

<?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>";

其中有一个变量,用于显示分组的每行的数量。

最佳答案

您可以使用此查询,按查询分组必须选择并提供聚合,这里我提供了计数,如果您需要一些适当的列,您可以相应地更改它...

            <?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>";
}
}
?>

关于php - 计算 SQL 组中的行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39854071/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com