Hamzat Luqman Hamzat Luqman - 6 months ago 230
jQuery Question

PHP and mysql WhatsApp style Chat Display

Can anyone guide me on how to display all messages from my chat database table in WhatsApp format Grouping Messages by Date i.e


[Today]

Janet:How are?

Jon: Am fine and you

[ Yesterday ]

John: Go to bed please

Janet: Okay dear, Good nite


CREATE TABLE IF NOT EXISTS
chat
(
id
int(10) unsigned NOT NULL,
from
varchar(255) NOT NULL DEFAULT '',
to
varchar(255) NOT NULL DEFAULT '',
message
text NOT NULL,
sent_by
varchar(111) NOT NULL,
created
datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
recd
int(10) unsigned NOT NULL DEFAULT '0'
) ENGINE=MyISAM AUTO_INCREMENT=229 DEFAULT CHARSET=latin1;

$result = mysql_query("SELECT *FROM (SELECT * FROM
chat
WHERE
from
= '$my_id' AND
to
= '$chat_with' OR
from
= '$chat_with' AND
to
= '$my_id' ORDER BY
created
DESC LIMIT $start, $limit )tmp
ORDER BY tmp.created ASC") or die(mysql_error());

while($row = mysql_fetch_array($result)){
print"$row['from']";
echo parse_smileys(make_clickable(nl2br(stripslashes($row['message']))), $smiley_folder);
print"$row['created'] @ $msg_time";
}

Answer

You can try something like this:

$printedDays = array();

foreach ($messages as $message) {
    // make sure you are changing the format to match your storage date time
    $dateTime = DateTime::createFromFormat('Y-m-d H:i:s', $message['myMessageDateTime']);
    $dateTime->setTime(0, 0, 0);
    if (!in_array($dateTime, $printedDays)) {
        echo formatDate($dateTime) . '<br />';
        $printedDays[] = $dateTime;
    }

    echo $message['content'] . '<br />';
}

function formatDate(DateTime $dateTime)
{
    $now = new DateTime();
    $diff = $now->diff($dateTime);

    switch ($diff->d) {
        case 0:
            return '[Today]';

        case 1:
            return '[Yesterday]';

        default:
            return $dateTime->format('[l, d F Y]');
    }    
}

First you should get the messages in descending order by message date and time. The result would be something like:

[Monday, 15 May 2016]

John: Go to bed please

Janet: Okay dear, Good nite

[Yesterday]

John: Go to bed please

Janet: Okay dear, Good nite

[Today]

Janet:How are?

Jon: Am fine and you

PS: This is just a procedural style to help you understand how you can do it. Of course, there are many other possible ways to implement it. As well it can be improved to fulfill your requirements