jvictorbr jvictorbr - 1 month ago 6
MySQL Question

Show message "nothing found" query mysql pdo

I'm not managing to display a message nothing found when the table is empty this query, someone could say where I am going wrong?

<?php
$sqlRead = "SELECT * FROM dados ORDER BY name ASC";

try{
$read = $db->prepare($sqlRead);
$read->execute();
} catch (PDOException $e) {
echo $e->getMessage();
}
while ($rs = $read->fetch(PDO::FETCH_OBJ)){

?>

<h1><?php echo $rs->name; ?></h1>



Answer

I found the solution

<?php
  $sqlRead = "SELECT * FROM dados ORDER BY name ASC";

    try{
        $read = $db->prepare($sqlRead);
        $read->execute();
        $result = $read->rowCount();
    } catch (PDOException $e) {
            echo $e->getMessage();
    }

    if($result == 0){
       echo "NOTHING FOUND!";
    } else {
       while ($rs = $read->fetch(PDO::FETCH_OBJ)){
?>

 <?php echo $rs->name; ?>

<?php } } ?>

With the code above, can display the message if nothing is found in the database