PHP MySQL tutorial

Using COUNT Function in MySQL

This article explains how we can count number of values in a specific column where the values meet a specific criteria. To do so, the COUNT function is used in MySQL

The syntax of the COUNT function is as follows

FROM table
WHERE condition1, condition2 ....;

To number of all the values that meet specific criteria using COUNT function in MySQLi, pass the query for finding COUNT to the query function of the mysqli object. The following example counts the number of values for patient_age column where value is greater than or equal to 40.

Using COUNT Function in Mysqli

connect_error) {
    die("Connection not established: " . $connection->connect_error);
$query = "Use Hospital;";
// Using COUNT Function

$query = "SELECT COUNT(patient_age) ".
"FROM Patient ".
"WHERE patient_age >= 40";

$output = $connection->query($query);
$count = $output->fetch_row();

echo "Total number of retrieved rows is ". $count[0];


Download the code

In the above example the result returned by the query is stored in the first index of the array returned by the fetch_row() method. If you remove the where clause in the above query, COUNT will return total number of all the values in the patient_age column.

<<< SUM and AVG Functions in MySQLUCASE and LCASE Functions in MySQL >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .