小编典典

检查空结果(php,pdo,mysql)

mysql

拜托,有人能告诉我我在做什么错吗?我只是从表中检索结果,然后将它们添加到数组中。一切正常,直到我检查结果为空为止。

这将获得匹配项,将其添加到我的数组中,并按预期回显结果:

$today = date('Y-m-d', strtotime('now'));

$sth = $db->prepare("SELECT id_email FROM db WHERE hardcopy = '1' AND hardcopy_date <= :today AND hardcopy_sent = '0' ORDER BY id_email ASC");

$sth->bindParam(':today',$today, PDO::PARAM_STR);

if(!$sth->execute()) {
    $db = null ;
    exit();
}

while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
    $this->id_email[] = $row['id_email'] ;
    echo $row['id_email'] ;
}

$db = null ;
return true ;

当我尝试检查空结果时,我的代码返回“空”,但不再产生匹配结果:

$today = date('Y-m-d', strtotime('now'));

$sth = $db->prepare("SELECT id_email FROM db WHERE hardcopy = '1' AND hardcopy_date <= :today AND hardcopy_sent = '0' ORDER BY id_email ASC");

$sth->bindParam(':today',$today, PDO::PARAM_STR);

if(!$sth->execute()) {
    $db = null ;
    exit();
}

if ($sth->fetchColumn()) {
    echo 'not empty';
    while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
        $this->id_email[] = $row['id_email'] ;
        echo $row['id_email'] ;
    }
    $db = null ;
    return true ;
}
echo 'empty';
$db = null ;
return false ;

与往常一样,我们将提供任何帮助。谢谢!


阅读 317

收藏
2020-05-17

共1个答案

小编典典

您这样做时会丢掉结果行$sth->fetchColumn()。那不是您检查是否有任何结果的方法。你做

if ($sth->rowCount() > 0) {
  ... got results ...
} else {
   echo 'nothing';
}

相关文档在这里:http :
//php.net/manual/zh/pdostatement.rowcount.php

2020-05-17