我正在运行一个while循环来获取每个对话的最新消息,但是我收到了错误
[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 } ?>
感谢。
答案 0 :(得分:2)
GROUP BY子句在WHERE之后,在ORDER 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 ");
答案 1 :(得分: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
语句应该在ORDER BY
之前,然后是LIMIT
。您在声明中的排序是错误的。
此外,就像Mike提到的那样,你应该使用mysql_error()
来查看MySQL抛出的错误。