tags:

views:

540

answers:

3

So I have a chatroom type of database where the text that a user inserts gets stored into a databse as their username in one field and their message in the other. I want to have my page output the database info, so that people can see each others messages. How do I do this?

Also, is it possible to make a for loop that checks to see if the database has been updated with a new message, therefore it reloads the page? (Then the page outputs the database info again to update everyones messages)

Please help.. i'm so confused.

+2  A: 

Take a look at MySQL functions in PHP manual. You need to connect to the server/database and run a select query to get the data from tables.

As for the loop: you could use JavaScript setInterval function and combine that with AJAX call to periodically poll for new records.

Milan Babuškov
A: 
  1. To read anything from a mysql database you would use the mysql_connect() and the mysql_query() functions eg:
$link = mysql_connect('localhost', 'root', '');
$results = mysql_query('select * from messages);

while($row = mysql_fetch_array($results))
{
    echo $row['username'] . ': ' . $row['message'].'<br />';
}
  1. To display new messages the best way would be to use AJAX and poll the database from there, either loading a separate page into a DIV or getting XML back and placing into HTML tags. I would recommend using JQuery for these kinds of tasks. Check http://www.sitepoint.com/article/ajax-jquery/ for an example.
Mladen Mihajlovic
A: 

Like the others have said, you will want to connect to your database and then query the table that you have the data in.

while($row = mysql_fetch_assoc($results))
{
    echo $row['username'] . " said: " . $row['message'] . "<br />";
}

I use mysql_fetch_assoc() instead of mysql_fetch_array() since the arrays are associative arrays (not indexed by integers, but rather by names (associations))

As for displaying the update on the page dynamically, that involves AJAX. Basically what that means is that your page will call out to a background script to get the new records from the database. This would require a new field in your 'messages' table, something like 'msg_delivered' that you could set to '1' when it has been fetched.

You should check out this if you are interested in making an AJAX chat client: http://htmltimes.com/javascript-chat-client-in-jquery.php

Thomas