$req_user = trim($_GET['user']);
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$get_data = "SELECT * FROM `users` WHERE uname = '$req_user'";
$result = mysql_query($get_data) OR die(mysql_error());
$rows = mysql_fetch_assoc($result);
$email = $rows['email'];
$gravatar = md5(strtolower(trim("$email")));
$user_likes = mysql_query("SELECT COUNT(*) FROM likes WHERE username = '$email'");
我正在尝试使用likes
字段中当前用户的电子邮件来计算数据库username
中的所有行。
(这是从userinfo.php?user=xxx
等链接获取信息的循环。)
当我回显$user_likes
时,没有输出。
代码有什么问题?
http://www.tutorialspoint.com/mysql/mysql-count-function.htm
答案 0 :(得分:2)
假设$gravatar = md5(strtolower(trim("$email")));
与此处的问题无关且不需要,您也可以对数据库使用一个查询来获取计数:
$req_user = trim($_GET['user']);
mysql_connect("$host", "$username", "$password") or die("cannot connect");
mysql_select_db("$db_name") or die("cannot select DB");
$get_count_query =
"SELECT COUNT(*)
FROM likes
WHERE username =
( SELECT email
FROM users
WHERE uname = '$req_user'
)
";
$result = mysql_query($get_count_query) or die(mysql_error());
$row = mysql_fetch_row($result);
$user_likes = $row[0];
答案 1 :(得分:1)
你没有拿到它......
这样做:
$result = mysql_query("SELECT COUNT(*) FROM likes WHERE username = '$email'");
$user_likes = mysql_fetch_row($result);
答案 2 :(得分:1)
首先,您需要正确比较电子邮件(不区分大小写):
"... WHERE UPPER(username) = '" . strtoupper($email) . "'"
然后$ user_likes是一个资源变量,它不会直接给你计数。
您需要先获取它:
$row = mysql_fetch_row($user_likes);
echo 'Count: ' . $row[0];
答案 3 :(得分:1)
你应该这样做:
$req_user = trim($_GET['user']);
mysql_connect("$host", "$username", "$password") or die("cannot connect");
mysql_select_db("$db_name") or die("cannot select DB");
$get_data = "SELECT * FROM `users` WHERE uname = '$req_user'";
$result = mysql_query($get_data) or die(mysql_error());
if ($rows = mysql_fetch_assoc($result)) {
$email = $rows['email'];
$gravatar = md5(strtolower(trim("$email")));
$get_data = "SELECT COUNT(*) FROM likes WHERE username = '$email'";
$user_likes = mysql_query($get_data) or die(mysql_error());
if ($row = mysql_fetch_row($user_likes)) {
$nbr = 1*$row[0];
} else {
// it could never happen ;-)
$nbr = 0;
}
} else {
// no match with this user!
$nbr = 0;
}
echo "This user likes $nbr times !";