Warm tip: This article is reproduced from serverfault.com, please click

其他-如何使用php和mysql为用户计数消息

(其他 - How to count messages for a user with php and mysql)

发布于 2020-11-27 20:05:37

我正在尝试计算每个用户收到的消息数。我有一个具有用户详细信息id, name等的用户。我在users_msgs其中创建了另一个表id, msg_id, user_id我想显示每个用户收到的邮件数。最好的方法是什么?

该Web应用程序有2000多个用户。因此该脚本必须选择所有这些脚本并计算它们的消息。我认为这不是最佳解决方案。

我认为将users_msgs表中1个用户的计数行作为计数,然后表中查询用户表及其ID的用户名users_msgs

我尝试选择所有用户,没有任何限制:

SELECT * FROM users

然后像这样遍历结果:

<?php

  while ($user = mysqli_fetch_assoc($users)) {
    $count = count_user_msgs($user['id']);
    echo "{$user['name']} messages: $count";
  }

?>

count_user_msgs函数如下所示:

<?php

$sql = "SELECT COUNT(id) as msgs_count FROM users_msgs WHERE user_id = ?";
$stmt = mysqli_stmt_init($db);
if (mysqli_stmt_prepare($stmt, $sql)) {
  mysqli_stmt_bind_param($stmt, 's', $user_id);
  mysqli_stmt_execute($stmt);
  $result = mysqli_stmt_get_result($stmt);
  $count = mysqli_fetch_assoc($result)['msgs_count'];
  return $count;
}
return false;

?>
Questioner
vajad57
Viewed
11
Felippe Duarte 2020-11-28 04:37:33

你需要按每个用户分组并获得计数:

$sql = "SELECT user_id, name, count(user_id) as msgs_count from table group by (user_id, name)";

$result = $mysqli->query($query)

while ($user = mysqli_fetch_assoc($users)) {
    $user_id = $users['user_id'];
    $msgs_count= $users['msgs_count'];
    $count[$user_id] = $msgs_count;
    echo "{$user['name']} messages: $msgs_count";
}