Klaus Jasper Klaus Jasper - 11 months ago 60
MySQL Question

PHP - How to Use ORDER BY and GROUP BY together

I created a table that contains

message, sender, to, time
I want group by sender and order by time this is my code

$query= mysql_query("SELECT * FROM `table` ORDER BY `time` GROUP BY `sender`")or die(mysql_error());
while($arr = mysql_fetch_array($query)){
$num = mysql_num_rows($query);
$msg = $arr ['message'];
echo '</br>';
echo $msg;

that shows me this error

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'GROUP BY
' at line 1

So how to fix that problem?



Answer Source

try this code

 $query= mysql_query("SELECT * FROM  `table`  GROUP BY `sender` ORDER BY `time` ")or  die(mysql_error());
                                             // ^^--will be before order                    
    $num = mysql_num_rows($query);  // out of the while loop
    while($arr = mysql_fetch_array($query)){
    $msg = $arr['message'].'<br />';
           // ^^--remove space here
    echo $msg;