0

我正在尝试从我的表 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

4 回答 4

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 准备好的语句!

于 2012-12-19T21:28:55.090 回答
0

尝试:

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

您可能还想阅读SQL Injection

于 2012-12-19T21:28:33.470 回答
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.";
于 2012-12-19T21:32:52.023 回答
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.";
于 2012-12-19T23:39:56.113 回答