1

I am trying to loop through data to make a chat system. I have made a php function:

function getLatestMessageTime() {
    $handler = new PDO('mysql:host=localhost;dbname=*****', '******', '*******');

    // Set the query \\
    $query = $handler->query('SELECT `time` FROM `messages`');

    // Loop through the data \\
    $latestTime = 0;
    while ($row = $query->fetch()) {
        if ($row['time'] > $latestTime) {
            $latestTime = $row['time'];
        };
    };

    // Return the latest message time \\
    Return $latestTime;
}

And I set my looping jQuery code:

var latestTime = <?php echo getLatestMessageTime(); ?>;
latestTimeLoop();
function latestTimeLoop() {
    if (latestTime < <?php echo getLatestMessageTime(); ?>) {
        $("#container").load('ajaxLoad.php?time='+latestTime);
    };

    document.log(latestTime + " - " + <?php echo getLatestMessageTime(); ?>);
    setTimeout(latestTimeLoop, 200);
}

But when I change the time in phpMyAdmin to be much higher than the rest of the data, it doesn't update in my console.logs. It seems like my query isn't occuring more than once within my function, it only grabs the data once instead of requesting it each time my javascript code loops.

Is there any way to reset the query each time to it grabs new info each loop?

View Full Code

1 Answer 1

1

use ORDER BY in your query and also limit the query to one.

$query = $handler->query('SELECT `time` FROM `messages` ORDER BY `time` DESC LIMIT 1');

Only last record details is needed to get the latest message time. thats why i said to use limit and modify php code according to it.

Sign up to request clarification or add additional context in comments.

2 Comments

So how would I set this into my $latestTime variable to return it?
$row = $query->fetch(); $latestTime = $row['time'];

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.