title: php-mysql: group by gives error
body: <p>I have messages table with the following columns:
  <code>id_message_parent,id_user_from,id_user_to,message,read_date,created,status</code> </p>
  
  <p>I need to select the last message for a user grouped by <code>id_message_parent</code> and tried a lot but all query gives white page of death "500 server error" or return the first in order not last like:</p>
  
  <pre><code>    {"messages":[{"id_message":"1","id_message_parent":"1","id_user_from":"1","id_user_to":"2","message":"\u0645\u0631\u062d\u0628\u0627 \u0627\u0646\u0627 \u0645\u0633\u062a\u062e\u062f\u0645 1","read_date":null,"created":"2016-10-17 18:13:39","status":"0"}]}
  
  //while it should be
  {"messages":[{"id_message":"2","id_message_parent":"1",.....}]}
  </code></pre>
  
  <p>Here is what I have tried:</p>
  
  <pre><code>$sql="SELECT *, max(id_message) as max_id FROM `messages` WHERE (`id_user_to`='".$id_user."' OR `id_user_from`='".$id_user."') and `status`='".$status."' GROUP BY `id_message_parent`";
  
  $sql="select * from `messages` where `id_message` in(SELECT *, max(id_message) as max_id FROM `messages` WHERE (`id_user_to`='".$id_user."' OR `id_user_from`='".$id_user."') and `status`='".$status."' GROUP BY `id_message_parent`) x";
  
  $sql="SELECT * FROM `messages` WHERE `id_message` IN (SELECT MAX(id_message) FROM `messages` WHERE (`id_user_to`='".$id_user."' OR `id_user_from`='".$id_user."') and `status`='".$status."') ORDER BY id DESC";
  
  $sql="SELECT * FROM (SELECT * FROM `messages` WHERE `id_user_to`='".$id_user."' OR `id_user_from`='".$id_user."' ORDER BY id DESC) a GROUP BY IF(`id_user_to` = '".$id_user."', `id_user_from`, `id_user_to`)";
  
  $sql="SELECT `id_message`, `id_message_parent`, `id_user_from`, `id_user_to`, `message`, `read_date`, `created`, `status`, GROUP_CONCAT(`id_message`, ',') FROM `messages` GROUP BY `id_message_parent`";
  </code></pre>
  
  <p>and more....
  here is the php function</p>
  
  <pre><code>$result = mysql_query($sql);    
  if (mysql_num_rows($result) &gt; 0){   
  $messgs=array();
  while ($messgs_info= mysql_fetch_array($result)){   
      $info = new Messages();
      $info-&gt;id_message=$messgs_info['id_message'];       
      $info-&gt;id_message_parent=$messgs_info['id_message_parent'];     
      $info-&gt;id_user_from=$messgs_info['id_user_from'];       
      $info-&gt;id_user_to=$messgs_info['id_user_to'];   
      $info-&gt;message=$messgs_info['message']; 
      $info-&gt;read_date=$messgs_info['read_date']; 
      $info-&gt;created=$messgs_info['created']; 
      $info-&gt;status=$messgs_info['status'];
  
      array_push($messgs, $info);
  }
      echo json_encode(array('messages' =&gt; $messgs));
  }
  </code></pre>