Php-mysql使用groupby计数行不起作用


Php mysql count row using groupby not working?

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被弃用不再使用,使用mysqlipdo

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