How to properly handle & ldquo; chat update & rdquo; in a discussion page?

advertisements

So I'm trying to make a chat program in JavaScript using AJAX, and PHP. I am currently updating the chat like this, and I'm sure it's very hard on my server:

<div id="messages">[no messages]</div>

This is whats in the file called ajax-load-messages.php

<?php
    $sql_posts_result = mysql_query("SELECT Post FROM Posts ORDER BY Date ASC LIMIT 50", $db) or die("Can't load post"."<br/>".mysql_error());

    if(!empty($sql_posts_result)){
        while($row = mysql_fetch_row($sql_posts_result)){
            echo '<div class="message-post">'.$row[0].'</div>';
        }
    }
?>

and that's called by this javascript:

setInterval(function(){
        $('#messages').load('/ajax-load-messages.php');
    }, 3000);

So every 3 seconds I load the last 50 messages to the #messages div. I know there's a way to handle this that isn't even like 10% as resource intensive, but I don't know where to start. How can I handle this better?


Give the table an int autoincrement id. Keep track of the highest id received (in the session maybe), and on next poll only look for ids higher than that (i.e. only records created since last poll).