Skip to content
Advertisement

How to count messages for a user with php and mysql

I’m trying to count number of messages each user got. I have a users with user’s detail id, name etc. I have created another table users_msgs where I have id, msg_id, user_id. I want to display count of messages each user got. what will be the best way to do it?

The web application have more than 2000 users. so the script have to select all of them and count their messages. I think this is not the best solution.

I thinking of count rows for 1 user from users_msgs table as count and then querying the users table for user’s name with his id from users_msgs table.

I have tried selecting all users without any limit:

SELECT * FROM users

then iterating over the results like so:

<?php

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

?>

The count_user_msgs function looks like this:

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

?>

Advertisement

Answer

You need to group by each user and get the count:

$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";
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement