PHP - Latest Selection Question

2

Good,

I created a cryp that shows all messages from the user limited to 3. My goal is for messages to show like this every time they're recent.

     MSG hora: 12:30 - OLA
     MSG hora: 12:31 - OLA
     MSG hora: 12:32 - OLA

The problem is that when there is a new message and there are already 3, it just does not update, it shows the old 3, just past +2 messages is that it shows but form ASC (top to bottom) example: p>

     MSG hora: 12:32 - OLA
     MSG hora: 12:31 - OLA
     MSG hora: 12:30 - OLA

And it should always show the most recent in the 3rd here:

     MSG hora: 12:30 - OLA
     MSG hora: 12:31 - OLA
     Mais recente ->>> MSG hora: 12:32 - OLA






     $message_from = "SELECT msg_content, msg_from, msg_date FROM public_messeger_reply WHERE msg_to = '". $_SESSION['u_id'] ."' AND msg_reply_id = '". $order_detail['ads_id'] ."' ORDER BY msg_date DESC LIMIT 3";
     $to_query = $con->query($message_from);


     if($to_query->num_rows > 0) {
       echo "<blockquote>";
        while($fetch_to = $to_query->fetch_assoc()) {
              echo "<p><b>Negociante:</b> ". $fetch_to['msg_content'] ." <small>". dateName($fetch_to['msg_date']) ."</small></p>";
              } 
      echo "</blockquote>";
     }
    
asked by anonymous 28.05.2018 / 01:38

2 answers

2

Use a subquery to get only the last 3 records, and then sort them up (% with%):

SELECT *
FROM (SELECT msg_content, msg_from, msg_date FROM public_messeger_reply
     WHERE msg_to = '". $_SESSION['u_id'] ."'
     AND msg_reply_id = '". $order_detail['ads_id'] ."'
     ORDER BY msg_date DESC 
     LIMIT 3) t
ORDER BY msg_date ASC;
    
28.05.2018 / 03:05
0

Another option: - for those who have difficulty setting up a query but know well php!

if($to_query->num_rows > 0) {
   echo "<blockquote>";
    while($fetch_to = $to_query->fetch_assoc()) {
      //concatena acrescentando uma virgula ao final de cada loop  
      $result .= "<p><b>Negociante:</b> ". $fetch_to['msg_content'] ." <small>". dateName($fetch_to['msg_date']) ."</small></p>,";
    } 

    //retira a ultima virgula       
    $result=substr_replace($result, ',', -1);

    // Quebra o texto nas "," e transforma cada pedaço numa matriz
    $divisor = explode(",", $result);

    // Inverte os pedaços
    $reverso = array_reverse($divisor);

    // Junta novamente a matriz em texto
    $final = implode(" ", $reverso); // Junta com espaço

    echo $final;      

  echo "</blockquote>";
}
    
28.05.2018 / 03:55