2012-02-19 56 views
1

我運行一個while循環來獲取最新的每個會話的消息,但我得到的錯誤SELECT *,LAST(DATE_TIME)

[18-Feb-2012 21:14:59] PHP Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /path/messages.php on line 44 

下面是完整的循環。它在我添加LAST(date_time)和GROUP BY對話之前有效,但我只想在每個對話中顯示最新消息,而不是每個消息。我怎樣才能做到這一點?

<?php 
    $current_user = user_info('id',1); //get logged in user id 
    $query = mysql_query("SELECT *, LAST(date_time) 
          FROM messages 
         WHERE user_to='$current_user' 
         ORDER BY date_time DESC 
         LIMIT 0,5 
         GROUP BY conversation"); 
    while($message = mysql_fetch_array($query)) { 
?> 
       <li><strong><?php user_info('first_name',0,$message['user_from']); ?> <?php $sender_last_name = user_info('last_name',0,$message['user_from']); ?></strong><span class="message_time"><?php echo time2str($message['date_time']); ?></span><br /> 
       <span class="message_description"><?php echo substr($message['content'],0,50); ?></span></li> 
       <?php } ?> 

謝謝。

回答

2

GROUP BY子句那張WHERE後,訂單之前BY子句:

$query = mysql_query("SELECT *, LAST(date_time) 
          FROM messages 
         WHERE user_to='$current_user' 
         GROUP BY conversation 
         ORDER BY date_time DESC 
         LIMIT 0,5 "); 
+0

不錯.....趕上..... – 2012-02-19 04:24:54

1

在查詢看,你似乎有一些問題,語句的順序。

看看在MySQL Manual on Select Statement

SELECT 
    [ALL | DISTINCT | DISTINCTROW ] 
     [HIGH_PRIORITY] 
     [STRAIGHT_JOIN] 
     [SQL_SMALL_RESULT] [SQL_BIG_RESULT] [SQL_BUFFER_RESULT] 
     [SQL_CACHE | SQL_NO_CACHE] [SQL_CALC_FOUND_ROWS] 
    select_expr [, select_expr ...] 
    [FROM table_references 
    [WHERE where_condition] 
    [GROUP BY {col_name | expr | position} 
     [ASC | DESC], ... [WITH ROLLUP]] 
    [HAVING where_condition] 
    [ORDER BY {col_name | expr | position} 
     [ASC | DESC], ...] 
    [LIMIT {[offset,] row_count | row_count OFFSET offset}] 
    [PROCEDURE procedure_name(argument_list)] 
    [INTO OUTFILE 'file_name' export_options 
     | INTO DUMPFILE 'file_name' 
     | INTO var_name [, var_name]] 
    [FOR UPDATE | LOCK IN SHARE MODE]] 

GROUP BY語句應該來之前再接着LIMITORDER BY。您在聲明中的排序錯誤。

此外,就像Mike提到的那樣,您應該使用mysql_error()來查看MySQL拋出的錯誤。

+0

啊,不知道mysql_error位在哪裏消失了.. – Sam 2012-02-19 10:47:45