PHP和MySQL - 从列中获取特定结果的数量

时间:2015-04-02 20:28:42

标签: php mysql

我有这个代码来获取一列中的结果中有多少结果:

$result = "SELECT name FROM users";

echo $result;

如何显示特定数量的特定字符串?例如,我想在“名称”列中搜索名称“Andrew”。 “Andrew”有20个结果。我该如何回应“20”?

2 个答案:

答案 0 :(得分:2)

你会COUNT他们:

$result = "SELECT COUNT(`name`) AS `NameCount` FROM `users` WHERE `name` = 'Andrew'";

对于所有名称,您可以这样做:

SELECT `name`, count(`name`) AS `NameCount`
FROM `users`
GROUP BY `name`

这会导致类似这样的事情:

name    |    NameCount
----------------------
Andrew  |           20
Bob     |            6
Carol   |          125

答案 1 :(得分:0)

如果您使用Mysqli,则可以使用$ num_rows。 Somelithing like:

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

if ($result = $mysqli->query("SELECT Code, Name FROM Country ORDER BY Name")) {

    /* determine number of rows result set */
    $row_cnt = $result->num_rows;

    printf("Result set has %d rows.\n", $row_cnt);

    /* close result set */
    $result->close();
}

/* close connection */
$mysqli->close();
?>

另外,你可以使用mysql count()函数,如:

$result = "SELECT count(*), name FROM users";