计算重复的列值并在php中打印计数

时间:2013-03-05 16:17:01

标签: php mysql echo

我想在我的php页面中打印计数结果。我有MySQL数据库,我想在列中打印相似值的数量。请帮帮我。

我试过这样做:

$query2="SELECT bname, COUNT(*) TotalCount
FROM brandnames
GROUP BY bname
HAVING COUNT(*) > 1
ORDER BY COUNT(*) DESC";
$result2 = mysqli_query($con,$query2) or die("Counting Error!: " . mysqli_error());

if ($row2=mysqli_fetch_assoc($result2)) {
    echo nl2br($row2 . "\n");

}

但它回应了“数组”

2 个答案:

答案 0 :(得分:1)

在此示例中,id是每行的唯一ID,myfield是您要为相似值计算的列。

SELECT a.myfield, COUNT(*) AS count FROM mytable a
  INNER JOIN mytable b ON a.myfield = b.myfield
  WHERE a.id <> b.id
  GROUP BY a.myfield
  ORDER BY COUNT(*) DESC

您的PHP可能如下所示:

<?php
$result = mysql_query("SELECT a.myfield, COUNT(*) AS count FROM mytable a
  INNER JOIN mytable b ON a.myfield = b.myfield
  WHERE a.id <> b.id
  GROUP BY a.myfield
  ORDER BY COUNT(*) DESC");

while ($row = mysql_fetch_object($result)) {
  print $row->myfield . ' - ' . $row->count . '<br />';
}
?>

答案 1 :(得分:0)

尝试

if ($row2=mysqli_fetch_assoc($result2)) {
   echo nl2br($row2['TotalCount'] . "\n");

}