创建一个简单的公告板涉及到几个关键步骤:
- 创建数据库和表:
CREATE DATABASE noticeboard;
USE noticeboard;
CREATE TABLE messages (
id INT AUTO_INCREMENT PRIMARY KEY,
author VARCHAR(50) NOT NULL,
message TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
- 创建一个简单的HTML表单来提交新公告:
<form action="submit.php" method="post">
Author: <input type="text" name="author" /><br />
Message: <textarea name="message"></textarea><br />
<input type="submit" value="Post" />
</form>
- 创建PHP脚本来处理表单提交并将数据插入到数据库中:
<?php
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "noticeboard";
// 检查输入是否为空
if(empty($_POST["author"]) || empty($_POST["message"])) {
die("All fields are required.");
}
// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);
// 检查连接
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$stmt = $conn->prepare("INSERT INTO messages (author, message) VALUES (?, ?)");
$stmt->bind_param("ss", $author, $message);
$author = $_POST["author"];
$message = $_POST["message"];
if($stmt->execute()) {
header("Location: success.php");
} else {
echo "Error: " . $stmt->error;
}
$stmt->close();
$conn->close();
?>
- 创建一个PHP脚本来显示公告:
<?php
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "noticeboard";
// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);
// 检查连接
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$result = $conn->query("SELECT * FROM messages ORDER BY id DESC");
if ($result->num_rows > 0) {
// 输出数据
while($row = $result->fetch_assoc()) {
echo "Author: " . $row["author"]. " - Message: " . $row["message"]. " - Posted on: " . $row["created_at"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
确保替换数据库连接信息中的your_username
和your_password
为实际的用户名和密码。这个公告板的简单版本就完成了,你可以根据需要添加更多功能,例如用户验证、分页显示公告、删除公告等。