Need to fetch chat from database in a sequence

Currently I am working on a chat plugin custom made by me.
Here is my db structure for chat table

+----+----+----+------+------+------+-------+
| ID | FR | TO | TEXT | TIME | FLAG | EMAIL |
+----+----+----+------+------+------+-------+

Now I need to fetch the chat using ajax but it is not fetching in a sequence in which it was created.
Here is my code:

Read More
$query = "SELECT * FROM `j18h_user_chat` WHERE `fr` = '$nm' AND `to` = '$name' ORDER BY time";
$query2 = "SELECT * FROM $table WHERE `fr` = '$name' AND `to` = '$nm' ORDER BY time";

$abc = $wpdb->get_results($query);
$abc2 = $wpdb->get_results($query2);

echo "<div class='log'><div class='lef'>";

foreach ($abc as $key )
{
    echo '<div class="ui-chatbox-msg left" style="display: block; max-width: 285px;"><b><img class="usr" src="'.$key->email.'">  </b><span>'.$key->text.'</span></div>';
}

echo "</div><div class='rig'>";

foreach ($abc2 as $key2 )
{
    echo '<div class="ui-chatbox-msg right" style="display: block; max-width: 285px;"><b><img class="usr" src="'.$key2->email.'">  </b><span>'.$key2->text.'</span></div>';
}

Here the messages are stored one by one.
In first query I am fetching messages which i typed and in second which user typed.
So can anyone tell me how to fetch the chat in same sequence as it was created.

Related posts

1 comment

  1. Change your query to:

    SELECT * FROM `j18h_user_chat` 
    WHERE (`fr` = '$nm' AND `to` = '$name') OR (`fr` = '$name' AND `to` = '$nm')
    ORDER BY time
    

    Then to determine what class (left or right) to add to your div, something like this may work. (Note: I’m going under the impression $nm is the current user)

    foreach($abc as $key)
    {
        echo '<div class="ui-chatbox-msg '. leftOrRight($key->fr, $nm) .'" style="display: block; max-width: 285px;"><b><img class="usr" src="'.$key->email.'">  </b><span>'.$key->text.'</span></div>';
    }
    
    function leftOrRight($from, $currentUser)
    {
        return ($from == $currentUser) ? "left" : "right";
    }
    

Comments are closed.