Question with mysql, ajax, php

I write a chat using php, mysql, ajax and jQuery. The name of my table in mysql messages, it has 3 columns id, message and date. With the help of the submit() function, I display my messages on the screen. How can I make it so that using the timedMsg() function, I can display messages from the server that have been added by others since my last message?


Answer 1, authority 100%

Well, firstly, sending a message does not mean that you need to remove the check interval on the server (this is just in case), respectively, you should have 2 XMLHttpRequest objects, one will deal with checking messages and the other sending (this can solve the problem of “conflict” requests, i.e. so that messages are checked even when the message is sent)

Well, in general, as an option, just keep it in the session, for example $_SESSION['lastMessageId']and look at it already on the server…

It can be stored in cookies, it can be stored in display:none html element, it’s not so important…
And of course, + you need to look at this value on the server … Having implemented all this, you will foresee the case of a slow Internet connection, and + possible conflict of requests … (if you have not already implemented this naturally)


Answer 2

Send a request to the server and see if there are any messages, for example, with an id greater than the id of your last message. And if there are any, then give them to the client. It’s simple.


Answer 3

First, there should be a user field in the table (who sent this message).
Then the request will be like this:

$sql = 'select * from `messages` where `id` > ( select `id` from `messages` where `user` = '.$uid.' order by `date` desc limit 0,1 )';

Pay attention to $uid, you need to put the person’s id there