PHP: Check mysql database every 10 seconds for any new rows

26,183

Solution 1

This is what you need. We need set time for ajax auto reload. Don't put everything in one page. Because you must reload page to refresh data. That is bad solution.

Call jQuery Ajax Request Each X Minutes

Solution 2

Use MySQL Event Scheduler.

Below link will guide you through .

http://www.9lessons.info/2012/10/mysql-event-scheduler.html.

I think best option in your case .

Solution 3

AJAX is probably the simplest solution. You can perform an AJAX request on the same page your PHP code is executing on if you really want to.

(function check() {
    $.get('mypage.php', function(data) {
        doSomethingWith(data);
        setTimeout(check, 5000); // every 5 seconds
    });
})();

Solution 4

PHP doesn't have a setInterval function. While I'm sure you can use a crontask to automate it on the server, you can also achieve this with some simple Javascript.

The concept you are trying to achieve is known as Short Polling. What you want to do is to have a setInterval function in Javascript that constantly makes AJAX requests to your PHP file which performs the check to the database for new messages. Your PHP should return that information to your script where you can then simply populate the user's screen.

There is also Long Polling where you simply maintain the connection and have a setTimeout to wait for messages to come in. You can find more information yourself and if you have questions, you can come back here.

A good video about this:

https://www.youtube.com/watch?v=wHmSqFor1HU

Hope this helps.

Share:
26,183
blackhawk338
Author by

blackhawk338

Updated on April 21, 2020

Comments

  • blackhawk338
    blackhawk338 about 4 years

    I am making a php chat and am starting the php checking database part. So when a user types something into the chat, it gets recorded in the MySQL database, how would I check the database every 10 seconds so that one user's chat would update with new messages from other users. I know that you can use an ajax request to a page with an interval, but I want the php to be on the same page, instead of having to use numerous pages. This is the code for checking the database

    <?php
    $con = mysqli_connect('host','user','pass','database');
    $query = mysqli_query($con,"SELECT * FROM `messages`");
    while ($row=mysqli_fetch_assoc($query)) {
     $user = $row['user'];
     $message = $row['message'];
     echo 'User: ',$user,' Message: ',$message;
    }
    ?>
    

    Thanks in advance anyone!