You're going to have a few things to do:
- Pick a data store. MySQL is a popular choice when working with PHP. It doesn't sound like this'll be high-volume, so most any persistent store would work.
- When accepting input, you'll need to sanitize it for insertion into the DB (again, if using MySQL, check the docs), and then you'll execute an INSERT statement to put it into the database.
- When displaying the page, you'll connect to the DB (check the docs), query data from the data store, loop over it, and echo each line after sanitizing it of any potentially malicious data.
A short example might be something like:
<?
// Assuming a database named "my_database" with a table called "chat_lines", which has "username", "line", and "timestamp" fields.
$db = mysql_connect("localhost", "username", "password");
mysql_select_db("my_database", $db);
// If data was posted to the script, scrub it and store it in the database.
if($_POST["username"] && $_POST["line"]) {
mysql_query(sprintf("INSERT INTO chat_lines (username, line, timestamp) VALUES (\"%s\", \"%s\", NOW())",
mysql_real_escape_string($_POST["username"]),
mysql_real_escape_string($_POST["line"])
));
}
// Fetch all lines from the database in reverse chronological order
$result = mysql_query("SELECT * FROM chat_lines ORDER BY timestamp DESC");
while($row = mysql_fetch_assoc($result)) {
echo sprintf("<div>%s said %s</div>", strip_tags($result["username"]), strip_tags($result["line"]));
}
?>
<form method="post">
<div>Username: <input type="text" name="username" /></div>
<div>Line: <input type="text" name="line" /></div>
<input type="submit" />
</form>
That example makes assumptions about users being allowed to enter whatever username they want (that is, it doesn't assume to implement the authentication system), the data store and the existence of the table and all that, but should get you started. The PHP documentation is pretty extensive, and can be very useful. In particular, read Getting Started and the Language Reference.
Chris Heald
2010-08-28 10:31:53