How to Check If Field is NULL or Empty with If Statement in PHP MySQL?

Feb 02, 2022 . Admin

Hi Dev,

This article will give you example of how to check if field is null or empty with if statement in PHP?. I explained simply about check if field is null or empty with if statement example in PHP. This tutorial will give you simple Check If Field is NULL or Empt PHP.

In this post, You'll learn use PHP check if column is null or empty in if statement. i will show you use of PHP check if column is null or empty in case statement.

Table: users_payment


So, let's see bellow solution:

Example : 1 index.php
<?php

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

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

$sql = "SELECT 
            id, 
            user_id, 
            charge,
            IF(status IS NULL or status = '', 'PENDING', status) as status 
        FROM `users_payment`";

$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] => PENDING
)
Array
(
    [id] => 3
    [user_id] => 3
    [charge] => 10
    [status] => PENDING
)
Array
(
    [id] => 4
    [user_id] => 4
    [charge] => 10
    [status] => FAIL
)
Example : 2 index.php
<?php

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

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

$sql = "SELECT 
            id, 
            user_id, 
            charge,
            CASE WHEN status IS NULL or status = ''
                THEN 'PENDING'
                ELSE status
            END as status 
        FROM `users_payment`";

$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] => PENDING
)
Array
(
    [id] => 3
    [user_id] => 3
    [charge] => 10
    [status] => PENDING
)
Array
(
    [id] => 4
    [user_id] => 4
    [charge] => 10
    [status] => FAIL
)
#PHP