开发者

MySQL Count function not working right

$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'");

I'm trying to count all of the rows in the database likes with the email of the current user in their username开发者_运维知识库 field.

(It's a loop to get info from links like userinfo.php?user=xxx.)

When I echo $user_likes there is no output.

What is wrong with the code?

http://www.tutorialspoint.com/mysql/mysql-count-function.htm


Assuming that $gravatar = md5(strtolower(trim("$email"))); is not related to the question here and not needed, you could also use one query to the database, to get the count:

$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];


You didn't fetch it...

Do it like this:

$result = mysql_query("SELECT COUNT(*) FROM likes WHERE username = '$email'");

$user_likes = mysql_fetch_row($result);


First you need to properly compare the emails (case insensitive) :

"... WHERE UPPER(username) = '" . strtoupper($email) . "'"

Then $user_likes is a resource variable, it won't give you the count directly.

You need to fetch it first :

$row = mysql_fetch_row($user_likes);
echo 'Count: ' . $row[0]; 


You should do that :

$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 !";
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜