如何在MYSQLi和Prepared Statements中使用COUNT()?

时间:2010-07-04 13:02:03

标签: php mysql count mysqli

我需要从特定用户的表中计算具有相同状态的人数。我想使用预准备语句,所以我做了类似这样的事情(不工作):

$sql = 'SELECT status, COUNT(personID) FROM user_persons GROUP BY status WHERE userID = ?';

if ($stmt->prepare($sql)) {
    $stmt->bind_param('i', $userID);
    $stmt->bind_result($status, $count);
    $stmt->execute();
    while ($stmt->fetch()) {
        $data[$status] = $count;
    }
}

我想得到一个这样的数组:

$data[favorite] = 126
$data[otherstatus] = 345

怎么做?

2 个答案:

答案 0 :(得分:2)

我相信GROUP BY应该在WHERE子句之后。

$sql = 'SELECT status, COUNT(personID) FROM user_persons WHERE userID = ? GROUP BY status'

您是否收到任何其他错误?或者它只是没有做你想做的事情?

答案 1 :(得分:0)

为它添加别名,例如:

$sql = 'SELECT status, COUNT(personID) AS count_p FROM user_persons WHERE userID = ? GROUP BY status';

...然后使用:

取出它

fetch_object:

$row->count_p

FETCH_ASSOC:

$row['count_p']