Elli Joshua Rey
Elli Joshua Rey

Reputation: 45

How to Show in Php if there is no value on database table

<?php 
    $stmt = $con->prepare("SELECT id FROM sample WHERE  ID = (SELECT MAX(id)  FROM sample)");
    $stmt->execute();
    $stmt->setFetchMode(PDO::FETCH_ASSOC);
    $result = $stmt->fetchAll();

    foreach ($result as $row2) {
        $auto1 = $row2['id'];

            if ($auto1 ===' ') {
                echo "There is no ID!";
            } else {
                echo $auto1; 
            }

    }
?>

it shows the maximum id if there is value on database but when i'm deleting all data to try if i get the result of "There is no id on ID!" it doesn't show .. help me pls

Upvotes: 2

Views: 779

Answers (1)

BizzyBob
BizzyBob

Reputation: 14740

Your code as it currently is won't hit your error message when zero rows are returned. The line where you would get this info is:

$result = $stmt->fetchAll();

The fetchAll() method will return FALSE if no rows are returned, so just check that value and display the error messages accordingly.

<?php 
    $stmt = $con->prepare("SELECT id FROM sample WHERE  ID = (SELECT MAX(id)  FROM sample)");
    $stmt->execute();
    $stmt->setFetchMode(PDO::FETCH_ASSOC);
    $result = $stmt->fetchAll();


    if($!result){
        echo "No rows found..!";
    } else { 
        foreach ($result as $row2) {
            $auto1 = $row2['id'];

            if ($auto1 ===' ') {
                echo "There is no ID!";
            } else {
                echo $auto1; 
            }
        }
    }
?>

Upvotes: 2

Related Questions