Alamri
Alamri

Reputation: 2182

Get num_row once for different values

I'm very new to PHP, I'm trying to get result from database of rows count. I have used below given method:

$result = $mysqli->query("SELECT * FROM donors WHERE blood_group = 'A+'");
$Apositive = $result->num_rows;

Now as you can see I have to execute this query for every blood group.

Is there any easier method to get all these results in one way ?

Upvotes: 0

Views: 92

Answers (1)

Mark Baker
Mark Baker

Reputation: 212412

SELECT blood_group, count(*) AS donor_count
  FROM donors
 GROUP BY blood_group

will return a series of results, one for each blood_group, with a count of the donors for that group in donor_count; and you can then just loop over the resultset

EDIT

$query = "SELECT blood_group, count(*) AS donor_count
      FROM donors
     GROUP BY blood_group";

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

    /* fetch associative array */
    while ($row = $result->fetch_assoc()) {
        printf (
            "Blood Group: %s has %d donors)\n", 
            $row["blood_group"], 
            $row["donor_count"]
        );
    }
}

Upvotes: 3

Related Questions