treehouse : what would you like to learn today?
Web Design Web Development iOS Development

Update PHP Automatically?

  • I want to automatically update my PHP "wall" (like Facebook).
    Here is a a basic version of how my script works:

    <table>
    <?php
    $query = mysql_query("SELECT * FROM wall");
    while ($row = mysql_fetch_assoc($query)){
    $post = $row['post'];
    $name = $row['name'];
    ?>
    <tr>
    <td>
    <?php echo($name); ?>
    </td>
    </tr>
    <tr>
    <td>
    <?php echo($post); ?>
    </td>
    </tr>
    <?php
    }
    ?>
    </table>


    Any ideas how I can automatically get new information from my database and update the HTML table. Transitions are not necessary but would be cool. If you could explain and give me a example code, that would truly be awesome :)

    - Thanks!
  • You'll need to do a JavaScript AJAX request to get the new information, then append that to the table
  • OK, but how?
  • give each of the posts a unique ID, Then use XHR to send the last ID to another PHP file which can workout from the last ID if there has been any new posts since and if there are return it to the page as JSON/XML and use JS to append/prepend it to the document

    jQuery will make this a lot easier -> http://api.jquery.com/jQuery.ajax/
  • Each post has a unique ID, but how would I do that? I really understand if you couldn't be bothered explaining with examples but I think I need that to understand this probably.
  • are you outputting the id to the html?
    it doesnt have to be in the id field, just create you own one in the TR, lets say
    <tr postID='22'> rest of the post in here</tr>
    then you can grab the last tr in the table
    var postID = $('table tr:last-child').attr('postID');
    Then post this value back to your server and use your PHP to workout what to send back
  • Hmm, first of all, it would be first-child since it's DESC.. And I get sending the value to the server, but not quite what I'm supposed to send back. I don't know ajax at all you see.