使用COUNT函数计算新邮件数?

时间:2012-12-19 21:25:58

标签: php mysql count messages

我正在尝试从我的表ptb_messages获取用户拥有的新消息数量,其中'read'设置为'0'

有人可以告诉我我哪里出错了。

我的表格如下:

id | from_user_id | to_user_id | subject | content | date_sent | read

1         2              4        hello     hello    2012-04-13    0

我正在使用此功能尝试显示用户拥有的未读消息数。

function check_new_messages() {
            global $connection;
            global $_SESSION;
            $query = "SELECT COUNT('read') FROM ptb_messages WHERE to_user_id =".$_SESSION['user_id']." AND ('read)'='0'";
            $check_new_messages_set = mysql_query($query, $connection);
            confirm_query($check_new_messages_set);
            return $check_new_messages_set;     
        }

<?php

$check_new_messages_set = check_new_messages();
while ($new = mysql_fetch_array($check_new_messages_set)) {

echo "There are ". $new['COUNT(read)'] ." items.";

}

 ?>

4 个答案:

答案 0 :(得分:3)

根本不需要COUNT那个字段; WHERE就够了。报价只是一点点就是:

$query = "SELECT COUNT(*) FROM ptb_messages WHERE to_user_id =".$_SESSION['user_id']." AND `read` = 0";

此外,请不要使用mysql_扩展名;它们在PHP 5.5中被弃用,并且很容易引入SQL注入漏洞。准备好PDO或MySQLi语句吧!

答案 1 :(得分:0)

尝试:

        $query = "SELECT COUNT(read) FROM ptb_messages WHERE to_user_id =".$_SESSION['user_id']." AND read = 0";

您可能还想阅读SQL Injection

答案 2 :(得分:0)

首先,我认为您的SQL可能需要调整:

SELECT COUNT('read') FROM ptb_messages WHERE to_user_id =".$_SESSION['user_id']." AND ('read)'='0'

不应该是:

SELECT COUNT(id) FROM ptb_messages WHERE to_user_id =".$_SESSION['user_id']." AND `read` = 0

然后这一行:

echo "There are ". $new['COUNT(read)'] ." items.";

应该是:

echo "There are ". $new[0] ." items.";

答案 3 :(得分:0)

好的,你确实需要查看Mysqli或PDO,据说,很明显你会有不同状态的列“读”.0 =未读,1 =读等等....

在这里,您可以使您的功能更通用,并允许您通过一个功能获得这些状态。像这样:

function check_new_messages($id,$state)
{
    $query ="SELECT COUNT(*)as newmessage FROM ptb_messages WHERE to_user_id =".$id." AND `read` ='".$state."'";
    $check_new_messages_set = mysql_query($query, $connection);
    confirm_query($check_new_messages_set);
    return $check_new_messages_set;     
 }
    $check_new_messages_set = check_new_messages($_SESSION['user_id'], '0' );
    while ($new = mysql_fetch_array($check_new_messages_set))
        {
            echo "There are ". $new['newmessage'] ." items.";
        }

以下是使用MYSQLI的示例。在此示例中,您可以返回行计数并回显它:

function check_new_messages($id,$state)
{
    $MessageCount = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
    if ($MessageCount->connect_errno)
    {
        echo "Failed to connect to MySQL: (" . $MessageCount->connect_errno . ") " . $MessageCount->connect_error;
        $MessageCount->close();
    }
    $values = $MessageCount->query("SELECT to_user_id FROM ptb_messages WHERE to_user_id =".$id." AND `read` ='".$state."'");
    if($count = $values->num_rows)
    {
        return $count;
    }
        return 0;
}

//像这样回电话

$Unread = check_new_messages($_SESSION['user_id'], '0' );
echo "There are ". $Unread ." items.";