简体   繁体   中英

How do I count rows with matching id?

I'm currently having some difficulty with determining if any rows match a specific user id. The code runs fine, but the if statement (if($notifs !== false) always returns true and hence "No notifications found" never displays. How do I write the statement to only check for "receive_id" that match the current session 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.'

&nbsp<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 says:

An empty array is returned if there are zero results to fetch, or FALSE on failure.

A query that matches zero rows is not a failure. It's a success at giving you the information that there are zero matching rows.

So you shouldn't compare with $notifs !== false , which compares exactly to the boolean false . You might like to compare with:

if (!$notifs)

This will also test for the empty array.

fetchAll only returns false if the query failed, but it's not failing. The result is an array. Your best to check if count($notifs) > 0 and also if $notifs === false for the possibility of the query failing.

Try

if ($stmt->RowCount() > 0) {
$notifs = $stmt->fetchAll(PDO::FETCH_ASSOC);
//code here
}

Instead of

$notifs = $stmt->fetchAll(PDO::FETCH_ASSOC);
if($notifs !== false) {
//code here
}

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