-2

I am creating a social network, I need to show the user how many people they follow and how many people follow them(followers and following). I want to add up the values in the user_to and user_from where the current user logged in is the person who followed someone or received a follow.

I am using this code below:

$user_follow_query = $con->prepare('SELECT SUM(user_to) FROM following WHERE user_to = ?');
$user_follow_query->bind_param("s", $username);
$user_follow_query->execute();
$user_follow_query->bind_result($followers);    
$user_follow_query_result = $user_follow_query->get_result();

while ($row = $user_follow_query_result->fetch_assoc()) {

    $followers = $row['user_to'];
}

But I'm getting this error:

( ! ) Notice: Undefined index: user_to in C:\wamp64\www\theshow\profile.php on line 38

On this line:

$followers = $row['user_to'];

Any help ?

GMB
  • 216,147
  • 25
  • 84
  • 135
thatguyy
  • 31
  • 5

1 Answers1

0

Your immediate problem is that you need to alias the column returned by the query so you can then access it it in the outer query.

So something like:

SELECT SUM(user_to) sum_user_to FROM following WHERE user_to = ?

Lets you then access the resulting column with $row['sum_user_to'].

But I also highly doubt that your query does what you want. If you want to count the followers, then that's the number of rows that satisfy the WHERE condition, so you want COUNT(*) rather than a SUM():

SELECT COUNT(*) no_followers FROM following WHERE user_to = ?

If you want both followers and followees, as explained in your question, then:

SELECT COUNT(*) no_relations
FROM following 
WHERE ? in (user_to, user_from)
GMB
  • 216,147
  • 25
  • 84
  • 135