实时更新收件箱消息

I need a suggestion with live update messages, here is my code:

<script>
    function fetch_messages(){
        var user_id = "1" // example id

        $.ajax({
            url: "do_fetch.php",
            type: "POST",
            data: { user_id : user_id },
            dataType: "json",
            success: function(data) {
                for (var i = 0; i < data.length; i++) {
                    $("#messages_list").append('<div id="'+data.id+'">'+data.message+'</div>');
                }
                setTimeout("fetch_messages()", 3000);
            }
        });
    }
    $(function(){
        fetch_messages();
    });
</script>

and there is div messages:

<div id="messages">
</div>

php code:

<?php
    include('connection.php')

    $user_id = $_POST['user_id'];
    $my_id = $_SESSION['user_id'];

    $sql = 'SELECT * FROM messages WHERE user_id = '.mysql_real_escape_string($user_id).' AND my_id = '.mysql_real_escape_string($my_id);
    $result = mysql_query($sql, $connection);

    echo json_encode($result);
?>

This code works, but I don't want to read all messages and show them, I need to load only new messages, so how should I do that? Do I need to put a hidden field with timestamp and to check with ajax for time later than that?

Save the id of the last message sent and then send that id via ajax, and query everything from newer than that id.

You'll need to add a "read" boolean field to your table. It should default to false, and then whenever messages are viewed, you should update all viewed messages to be read.

SELECT * FROM `messages` WHERE user_id=? AND my_id=? AND `read`=0;
UPDATE `messages` SET `read`=1 WHERE user_id=? AND my_id=?;

You can use , for example, next: setInterval(fetch_messages,5000) . Every five sec will sending request. Than on server save in session current time ( for first time ). During second request get from session last time, than get current time and fetch all rows between current and last time.

First you load with ajax just 20 messages in a ul

<ul>
  <li>message 1</li>
  <li>message 2</li>
  <li>message 3</li>
  <li>message 4</li>
  <li>message 5</li>
  <li id="{{message_date}}">message 6</li>
</ul>

Then get the last message id to get the date.

$('li').last().attr('id')

you can have a click button to load more.

var message_date = $('li').last().attr('id');
$.ajax({
    url: "do_fetch.php",
    type: "POST",
    data: { date : message_date },
    dataType: "json",
    success: function(data) {
        for (var i = 0; i < data.length; i++) {
            $("ul").append('<liid="'+ data.date+'">'+data.message+'</li>');
        }
    }
});

In the php file you select the messages with date > message_date with limit 30.

You can pass the user id too.