你有几件事要做:
-
选择数据存储。在使用PHP时,MySQL是一种流行的选择。听起来这不会是大容量的,所以大多数持久存储都可以工作。
-
在接受输入时,需要对其进行清理,以便插入到数据库中(同样,如果使用MySQL,
check the docs
),然后执行INSERT语句将其放入数据库。
-
check the docs
),从数据存储中查询数据,对其进行循环,并在清除任何潜在恶意数据后回显每一行。
<?
// 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>
这个例子假设用户可以输入他们想要的任何用户名(也就是说,它不假设实现身份验证系统)、数据存储和表的存在等等,但是应该让您开始。PHP文档非常丰富,非常有用。特别是阅读
Getting Started
Language Reference
.