PHP MySQL Case When Multiple Conditions Example

Feb 03, 2022 . Admin

Hello Friends,

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

In this post, You'll learn use case when in PHP with multiple conditions. i will show you use of PHP case when multiple conditions.

Here i will give you many example for PHP case statement with multiple conditions.

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 
            id, 
            user_id, 
            charge,
            CASE WHEN status = 1 THEN 'PAID'
                WHEN status = 2 THEN 'FAIL'
                WHEN status = 3 THEN 'WAIT'
                ELSE 'PENDING'
            END as status 
        FROM `user_payments`";

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

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

?>
Output:

Array
(
    [id] => 1
    [user_id] => 1
    [charge] => 50
    [status] => PAID
)
Array
(
    [id] => 2
    [user_id] => 2
    [charge] => 45
    [status] => FAIL
)
Array
(
    [id] => 3
    [user_id] => 3
    [charge] => 10
    [status] => PENDING
)
Array
(
    [id] => 4
    [user_id] => 4
    [charge] => 10
    [status] => PAID
)
Array
(
    [id] => 5
    [user_id] => 5
    [charge] => 66
    [status] => WAIT
)
It will help you...
#PHP