1

I've currently got a table with users and variable user status (1, 2, 3, 4, 5 etc). I am currently calculating the number of users in each status separately

$query = "SELECT COUNT(*) FROM users WHERE status = 1";
$result = $pdo->query($query);
$users1 = $result->fetchColumn();

$query = "SELECT COUNT(*) FROM users WHERE status = 2";
$result = $pdo->query($query);
$users2 = $result->fetchColumn();

etc

I could get a fetch, then loop through all the results and add each status but I was wondering if there is a better way to do it with a query?

2 Answers 2

2

You can use group by and get the list with the count

SELECT status, COUNT(*)  as my_count FROM users group by status;

NB with this you can't use fetchColumn .. but fetchRow .and access by key

Sign up to request clarification or add additional context in comments.

2 Comments

I'll still have to loop through the results to get the $users1/2/3 etc right?
yes .. correct you must loop over the result fof get each row and avcces by key 'status',,,and ''my_count' to the values of each row ....(but you have select row for each status ...not for each $user) ..
1

you jsut need to add status as group by

SELECT COUNT(*),status FROM users group by status

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.