tags:

views:

42

answers:

3

Hi everybody,

I've a page that show data inserted in a mysql db; I'd like (if it is possible) that this view page automatically update when a record is added to the db (data are not inserted from the same page or may be inserted from another user).

thanks in advance ciao h.

A: 

I know sure on the best method to do this, but and quick-and-easy solution would be to get the total number of rows in your table on page load. Then every x seconds use an AJAX script to re-check that table's row count. If it has changed you could have extra logic that then fetches the new rows.

Martin Bean
I think storing the timestamp of the last request, and then checking if there are newer messages makes more sense than checking the total amount of messages (what if someone deletes a message f.e.?)
Jasper De Bruijn
Indeed, that's another way of achieving the above. Just simply query the database for any rows after [last update time] if you're storing a time stamp with records.
Martin Bean
+3  A: 

First way (easiest but annoying):
Add a meta refresh to the page and the full page refreshes every x amount of time.

Second way (AJAX):
I'm assuming this is what you want.

  • Load default HTML page etc... lets call it index.php
  • On above page create a <div> element with style display:none like this

    <div id="mydata" style="display: none;"></div>
    
  • Create a PHP page that retrieves and formats the database data and prints it out in x format, i.e a table or p tags. no headers or page specific stuff just data and simple tags

  • On index.php put something like this

    <script type="text/javascript">
        function update() {
            $.ajax({
                url: 'http://www.example.com/getData.php?q=latest',
                success: function(response) {
                    $('#mydata'.html(response);
                }
            });
        }
        // .ready function
        $(function() {
            // do setup stuff here, I think there is a refresh timer or something
            // that you'd use to trigger it every x amount of time
            // i.e something like this
            update();
        });
    </script>
    

EDIT: AJAX HTTP streaming forces data out to users

Viper_Sb
A: 

I was thinking about this last night and realized that node.js (http://nodejs.org/) might be perfect for this if you're looking for an event driven system. There is a good tutorial on getting started using node.js at http://net.tutsplus.com/tutorials/javascript-ajax/learning-serverside-javascript-with-node-js/.

blcArmadillo