Skip to content
Advertisement

How to display messages from the database on left and right?

‘I made a simple chat box with php but the problem is i want to display my messages on the right and the other user messages on the left i made two while loops but they didn’t work. My table is like this (Sender – reciever – msg) I want to display each message ordered by time and on different places right side and left side

if (isset($_POST['user_id'])){
  $sender_id = $_POST['user_id'];
  $sql = "SELECT * FROM messages_sys WHERE send_id=$sender_id AND reciever_id=$uid";
  $sql_query = mysqli_query($conn, $sql);
  print_r($sql_query);

Advertisement

Answer

you can use ‘if’ statement inside for loop :

foreach($messages as $message){

   if($message->reciever == user_id){
     <div class="right">$message</div>

   }elseif($meesage->sender == user_id){
    <div class="left">$message</div>

   }

}

of course you have to open and close php tag before type html code inside

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement