How can i add total of user’s following me? The code I currently have displays ALL the user’s following me, instead of saying numbers of user’s following me
<?php
$friends = Friends::getFriendsForUser($data->id);
if (count($friends) > 0) {
$db = DB::getInstance();
foreach($friends as $friend_id) {
$friend = $db->query('SELECT name, username FROM users WHERE id = ?', array($friend_id));
if ($friend->count() == 1) {
echo '<table>
<tr>
<td><img src="images/avatar.png"></td>
<td><a href="profile.php?user='.escape($friend->first()->username).'">'.$friend->first()->name.'</a></td>
</tr>
</table>';
}
}
} else {
echo 'Not following anyone.';
}
?>
There are two easy ways for counting records (though there are more than just these two)–using the built-in row count method for whichever database query library you are using, or using the SQL COUNT() function in the mySQL query.
$friend = $db->query('SELECT COUNT(*) as `total`, `name`, `username` FROM `users` WHERE id = ?', array($friend_id));
if($friend){
if($row = $friend->fetch_assoc()) {
echo 'The total is:'.$row['total'];
}
}
$friend = $db->query('SELECT `name`, `username` FROM `users` WHERE id = ?', array($friend_id));
$total=0;
if($friend){
$total = $friend->num_rows;
echo 'The total is:'.$total;
}