PHP从SQL查询中获取重复值的总数

时间:2018-11-12 01:23:21

标签: php sql

我有此查询,该查询返回行列表以及重复行的时间,并带有TotalCount列:

SELECT X,
COUNT(*) as TotalCount
FROM table
GROUP BY X HAVING COUNT(*) > 1
ORDER BY COUNT(*) DESC

我在PHPMyadmin中执行此查询:

[X] [TotalCount]
 A       5
 B       6

我尝试将查询包含在脚本中,但以下内容为“ 2”:

echo $result->num_rows;

如何在PHP中获取“ 11”?

编辑:

我的查询是:

$sql="
    SELECT X,
    COUNT(*) as TotalCount
    FROM table
    GROUP BY X HAVING COUNT(*) > 1
    ORDER BY COUNT(*) DESC
    ";

$result = $conn->query($sql);
echo $result->num_rows;

我正在尝试做类似的事情

echo $row[TotalCount];

初始表是

[X]
A
A
A
A
A
B
B
B
B
B
B

1 个答案:

答案 0 :(得分:1)

代码行为正确,由于您有2行,它返回2。您实际上需要这些行的值,因此需要fetch结果对象。

$sql="
    SELECT X,
    COUNT(*) as TotalCount
    FROM table
    GROUP BY X HAVING COUNT(*) > 1
    ORDER BY COUNT(*) DESC
    ";
$result = $conn->query($sql);
while($row = $result->fetch_array())
{
     echo $row['TotalCount'] . PHP_EOL; // or '<br />' if in a browser;
}