mysql和php中的未读聊天消息

时间:2013-07-29 11:38:51

标签: mysql

在我的mysql数据库中,我有关于未读邮件及其收件人的数据。 所以我做了一个Mysql查询来判断谁和消息有多少。

SELECT author FROM messages WHERE recipient='$_SESSION[id]' and viewed=0

我得到的结果如下:

49 49 49 49 49 12 12 56

如何构造此数组以获得最终输出结果,如下所示:

You have 5 messages from member 49, 2 from member 12, 1 from member 56?

5 个答案:

答案 0 :(得分:3)

SELECT author, count(author) as 'nr' 
FROM messages WHERE recipient='$_SESSION[id]' 
       and viewed=0 
GROUP BY author

这将为您提供每行2列:第一行是作者ID,第二行(标记为'nr',根据需要更改)来自该作者的未读消息数。

请注意:您的代码可能容易受到SQL注入攻击。要格外小心,并可能了解准备好的陈述。

PS:请注意$_SESSION[id]会发出警告,因为id是一个未定义的常量,就像现在一样。记得在它周围加上引号。

答案 1 :(得分:2)

只是为了好玩......

SELECT REPLACE(
         CONCAT("You have ",
           GROUP_CONCAT(
             CONCAT(" ",ttl," messages from member ",author) 
           ORDER BY ttl DESC)
          ),"  "," ")a
 FROM 
    (
       SELECT author,COUNT(*) ttl   
         FROM messages 
        WHERE recipient = 1 
          AND viewed = 0
        GROUP 
           BY author
    ) x;

答案 2 :(得分:1)

这将根据您已经拥有的数组为您提供结果。

$results = array(49, 49, 49, 49, 49, 12, 12, 56);

$messages = array();

foreach($results as $author) {
    isset($messages[$author]) ? $messages[$author]++ : $messages[$author] = 1;
}

$display = '';

$first = true;
foreach($messages as $author => $count) {
    if($first) {
        $display .= sprintf('You have %s messages from %s', $count, $author);
    }
    else {
        $display .= sprintf(', %s messages from %s', $count, $author);
        $first = false;
    }
}

echo $display;

答案 3 :(得分:0)

$messages = array();
foreach ($results as $result) {
    $sendser = $result['sender'];
    if (!isset($messages['sender'])) {
        $messages['sender'] = array();
    }
    $messages['sender'][] = $result;
}

// Here you have your messages as entities sorted by sender in a map
// ...

if (count($messages) != 0) {
    $notice = "You have ";
    $firstSender = true;
    foreach ($messages as $sender=>$msgsFromSender) {
        $pattern = ($firstSender) ? "%d messages from member %s" : ", %s from member %s";
        $notice .= sprintf($pattern, count($msgsFromSender), $sender);
    }
    $notice .= ".";
}

// ...

答案 4 :(得分:-1)

SELECT author,count(author) 
from messages WHERE recipient='$_SESSION[id]' and viewed=0 
GROUP by author