如果存在数据库结果,请执行此操作,否则,执行此操作

时间:2014-02-25 19:57:24

标签: php database if-statement pdo

我正在检查数据库以查看是否存在数据匹配。如果有,输出一些HTML,如果没有,输出不同的HTML。

由于某种原因,此查询无效。数据库中的数据确实提供了匹配,但第一个HTML没有输出。

我觉得这与我使用'FALSE'有关...我应该这样做吗?

<?php

// Check current favourite status
$sql = "SELECT * FROM tbl_favourites WHERE user_id = :who AND favourite_id = :usernum AND favourite_active = '1' LIMIT 1";

$q   = $conn->prepare($sql); // the default way of PDO to manage errors is quite the same as `or die()` so no need for that
$q->bindValue(':who',$who,PDO::PARAM_INT);
$q->bindValue(':usernum',$usernum,PDO::PARAM_INT);
$q->execute();

if($r = $q->fetch(PDO::FETCH_ASSOC)!== false)
{
    echo "<div id=\"favourite\" class=\"favouriteOptionActive\" onclick=\"loadXMLDoc('indexFavourite')\">Selected as favourite</div>";
}       
else
{
    echo "<div id=\"favourite\" class=\"favouriteOption\" onclick=\"loadXMLDoc('indexFavourite')\">Add me as a favourite</div>";
}

?>

2 个答案:

答案 0 :(得分:1)

而不是SELECT *执行SELECT COUNT(*),因为您实际上并未使用任何查询过的数据。

$sql = "SELECT COUNT(*) FROM tbl_favourites WHERE user_id = :who AND favourite_id = :usernum AND favourite_active = '1' LIMIT 1";
$q   = $conn->prepare($sql);
$q->bindValue(':who',$who,PDO::PARAM_INT);
$q->bindValue(':usernum',$usernum,PDO::PARAM_INT);
$q->execute();
$found = $q->fetchColumn();

if ($found > 0) {
    // Do stuff
}
else {
    // Do other stuff
}

另请注意,您的评论the default way of PDO to manage errors is quite the same as or die() so no need for that为false。 PDO处理错误的默认方式是silently。如果您想要其他两种错误模式,您需要自己设置它们。

答案 1 :(得分:0)

<?php

$sql = "SELECT 1 FROM tbl_favourites WHERE user_id = ? AND favourite_id = ? 
        AND favourite_active = 1 LIMIT 1";
$q   = $conn->prepare($sql); 
$q->execute([$who, $usernum]);
$exists = $q->fetchColumn();
?>
<div id="favourite" class="favouriteOption<? if ($exists): ?>Active<? endif ?>" onclick="loadXMLDoc('indexFavourite')">
<? if ($exists): ?>
    Selected as favourite
<? else: ?> 
    Add me as a favourite
<? endif ?>
</div>