![](/img/trans.png)
[英]MySQL: How to return all rows in a table and count the amount of rows with matching ID from another table
[英]How do I count rows with matching id?
我目前在確定是否有任何行與特定用戶ID匹配時遇到一些困難。 該代碼運行良好,但是if語句(if($ notifs!== false)始終返回true,因此從不顯示“未找到通知”。我如何編寫該語句以僅檢查與當前會話匹配的“ receive_id” ID?
$user_id = $_SESSION['userID'];
if(isset($_POST["view"]))
{
$stmt = $user_notif->runQuery("SELECT * FROM tbl_users WHERE userID=:uid");
$stmt->execute(array(":uid"=>$user_id));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$stmt = $user_notif->runQuery("SELECT * FROM notif_follow WHERE receive_id= ? ORDER BY id DESC LIMIT 5");
$stmt->bindValue(1,$user_id);
$stmt->execute();
$notifs = $stmt->fetchAll(PDO::FETCH_ASSOC);
$notification = '';
if($notifs !== false)
{
foreach($notifs as $notif)
{
$send_id = $notif['send_id'];
$query2 = $user_notif->runQuery("SELECT id FROM following WHERE user1_id=:uid1 AND user2_id=:uid2");
$query2->execute(array(":uid1"=>$user_id,":uid2"=>$send_id));
$query2result = $query2->fetch(PDO::FETCH_ASSOC);
if($query2result !== false){
$follow .= '<a href="followoff.php?id='.$send_id.'"><button class="button">Remove Channel</button></a>';
}
else{
$follow .= '<a href="followon.php?id='.$send_id.'"><button class="button">Add Channel</button></a>';
}
$notification .= '
<li>
<div class="notifbox">
<strong style="color: #4b8ed3;">'.$notif["send_name"].'</strong><p style="color: #fff;"> has added you.</p>
'.$follow.'
 <a href="index.php?id='.$notif["send_id"].'"><button class="button">View Channel</button></a>
</div>
</li>
<div class="sectionheader3"></div>
';
}
}
else
{
$notification .= '<li><h2 style="color: #4b8ed3; padding: 10px;">No Notifications Found<h2></li>';
}
http://php.net/manual/en/pdostatement.fetchall.php說:
如果要獲取的結果為零,則返回空數組;如果失敗,則返回FALSE。
匹配零行的查詢並非失敗。 成功地為您提供了零匹配行的信息。
因此,您不應與$notifs !== false
進行比較,后者恰好與布爾值false
進行比較。 您可能要與以下內容進行比較:
if (!$notifs)
這還將測試空數組。
如果查詢失敗,則fetchAll
僅返回false
,但不會失敗。 結果是一個數組。 最好檢查count($notifs) > 0
以及$notifs === false
是否存在查詢失敗的可能性。
嘗試
if ($stmt->RowCount() > 0) {
$notifs = $stmt->fetchAll(PDO::FETCH_ASSOC);
//code here
}
代替
$notifs = $stmt->fetchAll(PDO::FETCH_ASSOC);
if($notifs !== false) {
//code here
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.