Jump to content

PDO counting functions.


Godz06

Recommended Posts

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.';
}

?>

Link to comment
Share on other sites

Well, if you have all of your friends in an array (which is what it seem you have) then that is quite simple.

 

<?php

$friends = Friends::getFriendsForUser($data->id);

$totalFriends = count($friends);

echo 'I have ' . $totalFriends . ' following me.';

?>

 

Of course, that means that your friends are stalkers, unless you guys are at a parade.  ;)

Link to comment
Share on other sites

In another side, you have problems with the performance.

You are doing a query for each user... And, that's sh**.

 

You should be something like that:

"get all the users with their data"

$friends = Friends::getFriendsForUser($data->id);
if (count($friends) > 0) {
    $db = DB::getInstance();
    $friendsWithData = $db->query('SELECT name, username FROM users WHERE id IN (?)', implode(',',$friends));
    
    foreach ($friendsWithData as $friend) {
        echo '<table>
            <tr>
            <td><img src="images/avatar.png"></td>
            <td><a href="profile.php?user='.escape($friend->username).'">'.$friend->name.'</a></td>
            </tr>
        </table>';
    }
} else {
    echo 'Not following anyone.';
}

With that, you are doing a only one QUERY at the DataBase and print HTML for each result. This is better.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.