How to Sum with If Condition in PHP MySQL Example

Jan 31, 2022 . Admin

Hi Dev,

This article will give you example of sum query with if condition in PHP example. I explained simply about PHP sum with if multiple conditions. This tutorial will give you simple example of MySQL sum with if condition statement.

In this post, You'll learn use sum with condition in PHP. I will show you use of sum with if condition in PHP. You can use this example of PHP get record sum with if condition.

Table: users_payment


So, let's see bellow solution:

index.php
<?php

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

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

$sql = "SELECT 
            SUM(CASE 
                WHEN type = 'CASH' 
                THEN amount 
                ELSE 0 
            END) AS total_cash,
            SUM(CASE 
                WHEN type = 'CREDIT_CARD' 
                THEN amount 
                ELSE 0 
            END) AS total_credit_card
        FROM `users_payment`";

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

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

?>
Output :
Array
(
    [total_cash] => 850
    [total_credit_card] => 400
)
#PHP