简体   繁体   中英

php - mysqli count rows with specific value

At the moment I'm able to count all the record's in a table with the value "Waiting" . This is done by using:

$query = "SELECT COUNT(*) AS SUM FROM jobs WHERE status='Waiting'";

When I want to echo the row count I just do:

echo $rows['SUM'];

How can I do it so it also count's all the record's in a table with the value "Ready" ?

This query will return all status count divided by status:

SELECT status, COUNT(status) AS tot FROM jobs GROUP BY status

The resulting set is something like this:

status       tot
-----------  ------
Waiting      123
Ready        80
...          56

So you want status='Waiting' or status='Ready' ? You can separate parameters with OR or AND ; for example:

$query = "SELECT COUNT(*) AS SUM FROM jobs WHERE status='Waiting' OR status='Ready'";

By using IN operator in your query.

$query = "SELECT COUNT(*) AS SUM FROM jobs WHERE status IN ('Waiting','Ready')";

Get group based( status ) counts by using GROUP BY operator

$query = "SELECT COUNT(*) AS SUM FROM jobs GROUP BY status";

Print the status based result.

//Create the `mysqli_connection` and assign to `$conn` variable.
$result = mysqli_query($conn, $query); 

if($result->num_rows>0)
{
    while($row = mysqli_fetch_assoc($result))
    {           
        echo "<br>status=" . $row['status'];
        echo "<br>SUM=" . $row['SUM'];
    }
}
SELECT count(status) AS 'count' FROM jobs GROUP BY status HAVING status='Ready'

This will count the records with the status = Ready. You use GROUP BY to get an aggregate on the status field. And because you have used GROUP BY, you use HAVING (which is the equivalent of WHERE in GROUP situations) to filter the data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM