2013-07-29 27 views
1

在我的mysql數據庫中,我有關於未讀消息及其收件人的數據。 所以我做了一個Mysql查詢來查詢誰和多少消息。mysql和php中的未讀聊天消息

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? 

回答

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

這會給你基於你已經有的數組的結果。

$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; 
+0

我忘了雙胞胎,是吧? :D – Powerslave

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

-1:收件人之後的語法錯誤;) –

+0

哦,是的,我從OP的代碼中拿了那一點。無論如何,用正確的答覆你已經快得多了! ;-) – MBaas

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 .= "."; 
} 

// ... 
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; 
相關問題