拜托,谁能告诉我这里我做错了什么?我只是从表中检索结果然后将它们添加到数组中.一切都按预期工作,直到我检查一个空的结果...
这将获得匹配,将其添加到我的数组并按预期回应结果:
$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 ;
Run Code Online (Sandbox Code Playgroud)
当我尝试检查空结果时,我的代码返回'empty',但不再产生匹配结果:
$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 ;
Run Code Online (Sandbox Code Playgroud)
一如往常,任何帮助表示赞赏.谢谢!
Mar*_*c B 87
当你这样做时,你会丢掉一个结果行$sth->fetchColumn()
.这不是你如何检查是否有任何结果.你做
if ($sth->rowCount() > 0) {
... got results ...
} else {
echo 'nothing';
}
Run Code Online (Sandbox Code Playgroud)
相关文档:http://php.net/manual/en/pdostatement.rowcount.php
jos*_*123 12
如果您可以选择使用fetchAll(),那么如果没有返回任何行,它将只是空数组.
count($sql->fetchAll(PDO::FETCH_ASSOC))
Run Code Online (Sandbox Code Playgroud)
将返回返回的行数.
小智 9
虽然这是一个老话题,但我认为我会考虑到最近我必须处理这个问题.
您不应该将rowCount用于SELECT语句,因为它不可移植.我使用isset函数来测试select语句是否有效:
$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");
//I would usually put this all in a try/catch block, but kept it the same for continuity
if(!$sth->execute(array(':today'=>$today)))
{
$db = null ;
exit();
}
$result = $sth->fetch(PDO::FETCH_OBJ)
if(!isset($result->id_email))
{
echo "empty";
}
else
{
echo "not empty, value is $result->id_email";
}
$db = null;
Run Code Online (Sandbox Code Playgroud)
当然,这仅适用于单个结果,就像循环数据集时一样.
小智 8
$sql = $dbh->prepare("SELECT * from member WHERE member_email = '$username' AND member_password = '$password'");
$sql->execute();
$fetch = $sql->fetch(PDO::FETCH_ASSOC);
// if not empty result
if (is_array($fetch)) {
$_SESSION["userMember"] = $fetch["username"];
$_SESSION["password"] = $fetch["password"];
echo 'yes this member is registered';
}else {
echo 'empty result!';
}
Run Code Online (Sandbox Code Playgroud)