2

I can not seem to come over this easy problem.

I have the following code, where I select the column "status" from a table. There's three different values of "status", 0, 1 and 3.

I would like to count how many 0's there are, 1's and 2's, so that I can display them via <?php echo $accepted; ?> etc.

<?php 

    $sql = "SELECT status FROM applications";
    $result = mysqli_query($db, $sql);
    $row = mysqli_fetch_array($result, MYSQLI_NUM);
    $array = array_count_values($row);
    $pending = $array[0];
    $accepted = $array[1];
    $denied = $array[2];


?>

MYSQL_NUM changed to MYSQLI_NUM accordingly to comment, thank you.

9
  • Did you print_r($array)? What did you see? Commented Feb 3, 2017 at 20:10
  • I got this: Array ( [2] => 1 ) The sql table contains 4 rows, 2 with status=2, 2 with status=1. Commented Feb 3, 2017 at 20:11
  • for one thing MYSQL_NUM should read as MYSQLI_NUM Commented Feb 3, 2017 at 20:15
  • now you went and used code from an answer below but didn't include "The code I used given in an answer did not work....". What you should have done was, left the question intact and place a comment under the answer. Now that person could get downvoted because of that. Edit: as you seem to have done now. IMHO, you should have left your code the way it was. Commented Feb 3, 2017 at 20:17
  • 1
    I've rolled the question back. Commented Feb 3, 2017 at 20:20

1 Answer 1

5

A simple way is get these count using SQL

  $sql = "SELECT `status`, COUNT(*) as cnt FROM applications GROUP BY `status`";

you have an array of so you should

 while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
 {
   echo "status = " . $array['status'] . ' = ' . $array['cnt'] .'<br />';
 } 
Sign up to request clarification or add additional context in comments.

8 Comments

You should accept this answer it's the correct way to go but honestly you need to better you code in small applications this is fine but if you r looking to scale up you will regret this sorta code later
@JoséphFlames your comment if for me or for the OP ... and if you can please explain better .. ..
I've updated the questions with my new code, The array result is now: Array ( [0] => 1 [1] => 2 ) , how comes?
It was for Adam and I mean for one he is using sql which is depreciated and secondly he needs to use prepared statementz
OP is using mysqli_ and you have mysql_fetch_array and MYSQL_ASSOC both missing I's Edit: where Martin missed one. Edit: there we go ;-)
|

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.