Reputation: 29
I want to show messages as receiver on right and sender on left here's my query below:
<?php
$mesajsor=$db->prepare("SELECT * FROM mesaj where kullanici_gon=:send_id and kullanici_gel=:receiver_id
order by mesaj_zaman ASC");
$mesajsor->execute(array(
'send_id' => $_GET['kullanici_gon'],
'receiver_id' => $_GET['kullanici_gel']
));
$say=0;
while($mesajcek=$mesajsor->fetch(PDO::FETCH_ASSOC)) {
$say++;?>
How may I implement the foreach to that query?
foreach($messages as $message){
if($message->kullanici_gel == receiver_id){
<div class="right">$message</div>
}elseif($message->kullanici_gon == send_id){
<div class="left">$message</div>
}
}
Upvotes: 2
Views: 32
Reputation: 16804
You probably want to do this in two separate loops, like this:
echo '<div class="right">';
foreach($messages as $message){
if($message->kullanici_gel == $receiver_id) {
echo '<div class="message">$message</div>';
}
}
echo '</div><div class="left">';
foreach($messages as $message){
if($message->kullanici_gon == $send_id) {
echo '<div class="message">$message</div>';
}
}
echo '</div>';
To prevent writing code twice you could use functions. For instance:
function displayMessage($message)
{
echo '<div class="message">$message</div>';
}
echo '<div class="right">';
foreach($messages as $message){
if($message->kullanici_gel == $receiver_id) {
displayMessage($message);
}
}
echo '</div><div class="left">';
foreach($messages as $message){
if($message->kullanici_gon == $send_id) {
displayMessage($message);
}
}
echo '</div>';
Especially because displaying a message is probably more complicated than you let us believe.
Upvotes: 1