How to use COUNT() with MYSQLi and Prepared Statements?
I need to count the number of persons with the same status from a table for a specific user.. I want to use prepared statements so I did something like this (not working):
$sql = 'SELECT stat开发者_运维技巧us, 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;
}
}
I want to get an array like this:
$data[favorite] = 126
$data[otherstatus] = 345
How to do it?
I believe the GROUP BY should be after the WHERE clause.
$sql = 'SELECT status, COUNT(personID) FROM user_persons WHERE userID = ? GROUP BY status'
Are you getting any other errors? Or was it just not doing what you wanted?
Put an alias to it, e.g:
$sql = 'SELECT status, COUNT(personID) AS count_p FROM user_persons WHERE userID = ? GROUP BY status';
...then pick it up using:
fetch_object:
$row->count_p
fetch_assoc:
$row['count_p']
精彩评论