简体   繁体   中英

If no results in table show X, PHP MySQL

I have a query on my site and if there is no results, I'd like to say something else rather than have a blank page...

    $sth = $conn->prepare("SELECT * FROM directory WHERE user_active != '' AND County = :county");
    $sth->execute(array(':county' => $county));

    $c = 1;
    while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
        RETURNED DATA GOES HERE
    $c++;
    }
$sth->execute(array(':county' => $county));
if ($sth->rowCount() == 0) {
   echo 'no rows';
} else {
   while(yada yada yada) { ... }
}

Relevant docs: http://php.net/manual/en/pdostatement.rowcount.php

You're counting the results in $c , so you can check which value that has by appending your code with this:

if($c == 1) { // Counter is stuck at 1
    echo "No results were found.";
}

2种可能的解决方案,执行SELECT COUNT执行fetchall检查并稍后显示结果

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM