Php-mysql使用groupby计数行不工作?
表:测试表
__________________________
| id | name | note |
| 1 | aaa | 234234234 |
| 2 | aaa | kjhkjhkjj |
| 3 | bbb | jhghjgjjj |
| 4 | bbb | uiyiuyutt |
<?PHP
$result = mysql_query("SELECT COUNT(*) FROM `test_table` GROUP BY name");
$row = mysql_fetch_row($result);
mysql_free_result($result);
$row_result = $row[0];
echo $row_result;
?>
当我测试这个代码时,它是回声1
我想得到结果2
我该怎么办?
您应该循环结果:
$result = mysql_query("SELECT name, COUNT(id) cnt FROM `test_table` GROUP BY name");
while ($row = mysql_fetch_assoc($result)) {
echo $row['name'].' : '.$row['cnt'];
}
mysql_free_result($result);
当然,您应该停止使用mysql_
函数——它们已经被弃用很长时间了。
mysql
被弃用不再使用,使用mysqli
或pdo
<?PHP
$result = mysql_query("SELECT COUNT(name) FROM `test_table` GROUP BY name");
if ($result) {
while ($row = mysql_fetch_row($result)) {
$row_result = $row[0];
echo $row_result;
}
mysql_free_result($result);
}
?>