error
error

Reputation: 83

Why isn't my count going up with my while statement php?

I have a table named "records" and I have a column named "gender" with values of "M" and "F". I would like to tally the number of males and females and echo them onto my html document but I keep getting 0 as my output.

   $sql = "SELECT * FROM records";
   if($result = mysqli_query($conn, $sql)){
      $genderM = 0;
      $genderF = 0;

      while($row = mysqli_fetch_array($result)){
         $gender = $row['gender'] . "<br> \n";
               
         if ($gender == 'M') {
             echo "TRUE <br> \n";                  
             $genderM++;
         }
         if ($gender == 'F') {
             $genderF++;
         }
         else {
             echo '';
         }
     }
     echo $genderM . '<br>';
     echo $genderF . '<br>';
 } 
 mysqli_close($conn);

Upvotes: 0

Views: 43

Answers (3)

REDRUM
REDRUM

Reputation: 9

You can use the array_count_values function to make things alot cleaner.

$array = {"F", "M", "F"}
print_r(array_count_values($array));

output:

Array
(
 [F] => 2
 [M] => 1
)

Upvotes: 0

white-imp
white-imp

Reputation: 323

MySQL has better option to recieve desirable result for you - SELECT COUNT(*).

$db = new mysqli("localhost", "db_user", "db_pass", "db_name");
$result = $db->query("SELECT COUNT(*) FROM `records` WHERE `gender` = M");
$row = $result->fetch_row();
echo 'COUNT GENDER M : ', $row[0];

And then do the same for F gender.

As you can see - no need to make while loop an handle each row with counter.

Have a look at official doc https://www.php.net/manual/ru/mysqli.query.php

Upvotes: 0

cOle2
cOle2

Reputation: 4784

You are adding "<br> \n" to $gender so the comparison does not work.

You might be better off checking $row['gender'] instead, ie

if ($row['gender'] == 'M') {
... etc

Upvotes: 3

Related Questions