[英]Output distinct values in SQL column with PHP
I have a table with two collumns (shortened), NAME and CATEGORY. 我有一张桌子,上面有两个列(简称),NAME和CATEGORY。
I want to output the number of distinct categorys. 我想输出不同类别的数量。 For an examle: Sport : 5 , Houses : 10.
例如:运动:5,房屋:10。
I use this one: 我用这个:
$test = mysqli_query($con,"SELECT category, COUNT(category) as count FROM tablename GROUP BY category ORDER BY count DESC");
This work then I run the code in SQL Shell, but I have no clue on how to output it in PHP. 这项工作然后我在SQL Shell中运行代码,但是我不知道如何在PHP中输出代码。 I have searced Google up and down without any successfull solution.
我已经在没有任何成功解决方案的情况下在Google上下搜索。
Any help? 有什么帮助吗?
I want to output it in a table format. 我想以表格格式输出它。
EDIT: Here is my full code: (tablename is changed, and $con is removed) 编辑:这是我的完整代码:(更改表名,并删除$ con)
$test = mysqli_query($con,"SELECT DISTINCT lkategori, COUNT(lkategori) as count FROM tablename GROUP BY lkategori ORDER BY count DESC");
while($row = mysql_fetch_array($test)) {
echo $row['lkategori'] . ":" . $row['count'];
die("test");
}
$test = mysqli_query($con,"SELECT DISTINCT lkategori, COUNT(lkategori) as count FROM tablename GROUP BY lkategori ORDER BY count DESC");
echo "<table border='1'>";
while($row = mysqli_fetch_array($test)) {
echo "<tr>";
echo "<td>" . $row['lkategori'] . "</td>";
echo "<td>" . $row['count'] . "</td>";
echo "</tr>";
}
echo "</table>";
This will output all the categories and the count returned by the sql statement into a table. 这会将所有类别和sql语句返回的计数输出到表中。 Also as a sidenote you should look into PDO.
另外,还应注意PDO。
EDIT: to make sure you do get the distinct values you should use the DISTINCT keyword in your sql statement: 编辑:确保您确实获得了不同的值,您应该在sql语句中使用DISTINCT关键字:
$test = mysqli_query($con,"SELECT DISTINCT category, COUNT(category) as count FROM tablename GROUP BY category ORDER BY count DESC");
use this 用这个
while($row = mysqli_fetch_array($test)) {
echo $row['lkategori'] . ":" . $row['count'];
die("test");
}
Thanks
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.