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
https://forums.phpfreaks.com/topic/284313-pdo-counting-functions/
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.  ;)

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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.