PHP MySQL CASE WHEN with Count Function Example

Feb 04, 2022 . Admin

Hello Friends,

This article will give you example of PHP case when with count function example. I explained simply about case when with count in PHP query. This tutorial will give you simple how to use count function in case statement in PHP.

In this post, You'll learn count function in case statement in PHP example. i will show you use of can we use count function in case statement PHP.

Here i will give you many example for count function in case statement example in PHP.

Table: user_payments


So, let's see bellow solution:

index.php
<?php

$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "db_php";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

$sql = "SELECT 
            COUNT(CASE 
                WHEN status = '1'
                THEN 1 
                ELSE NULL 
            END) AS total_paid_payment,
            COUNT(CASE 
                WHEN status = '0' 
                THEN 1 
                ELSE NULL 
            END) AS total_fail_payment
        FROM `user_payments`";

$result = $conn->query($sql);

while ($row = $result->fetch_assoc()) {
    echo '<pre>';
    print_r($row);
}

?>
Output:
Array
(
    [total_paid_payment] => 3
    [total_fail_payment] => 2
)
It will help you...
#PHP