计算朋友数量并显示为数字PHP
I have been creating a social networking site and have a friends system in place where the users can add/remove each other and it displays the users friends and profile pictures. All i need now is just to retrieve a total number of friends rather than the friends being listed individually for example (Sam has 21 friends). My 'friends' table looks like this.
id user_one user_two
4 3 9
5 3 7
6 11 3
I have tried to run a query:
$friend_count = mysql_query("SELECT count(*) FROM friends WHERE
($user_one = '$id' AND $user_two = '$id')";
But i am not sure how to then display the number or if this is even along the right lines.
I am fairly new to PHP so any help would be greatly appreciated!
我一直在创建一个社交网站,并且有一个朋友系统,用户可以在其中添加/删除对方 它显示用户朋友和个人资料图片。 我现在需要的只是检索朋友总数而不是单独列出的朋友(Sam有21个朋友)。 我的'朋友'表看起来像这样。 p>
id user_one user_two
4 3 9
5 3 7
6 11 3
code> pre >
我试图运行查询: p>
$ friend_count = mysql_query(“SELECT count(*)FROM friends WHERE
($ user_one = '$ id'AND $ user_two ='$ id')“;
code> pre>
但我不知道如何显示数字或者是否沿着 正确的行。 p>
我是PHP的新手,所以任何帮助都将不胜感激! p>
div>
your query should be:
$friend_count = mysql_query("SELECT count(*) FROM friends WHERE
($user_one = '$id' OR $user_two = '$id')");
you should use mysqli because mysql is deprecated, so you can do like this:
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
$query = mysqli_query($link, "SELECT count(*) as count_friends FROM friends WHERE
($user_one = '$id' OR $user_two = '$id')");
$row = mysqli_fetch_array($query);
$count_friends = $row['count_friends'];
See what you're doing is this:
SELECT count(*) FROM friends WHERE ($user_one = '$id' AND $user_two = '$id')
It is looking in friends for rows where user_one AND user_two (which should not be variables... or between brackets) are the same.
So for something to be counted: user_one must be user_two
I imagine your intention is two check whether $id is either found in user_one or user_two throughout the table.
Meaning you need OR and not AND
Corrected Select statement:
SELECT count(*) FROM friends WHERE user_one = '$id' OR user_two = '$id'
UPDATE - Should do what you need:
$select= "SELECT count(*) FROM friends WHERE user_one = '$id' OR user_two = '$id'";
$conn= mysqli_connect("localhost", "USER", "PASSWORD", "test");
$query = mysqli_query($conn, $select);
$row = mysqli_fetch_array($query);
echo reset($row);