PHP 数据库留言板是一个简单的 Web 应用程序,允许用户通过 Web 界面提交留言,并将这些留言存储在数据库中。用户可以查看所有已提交的留言。这个应用通常涉及以下几个基础概念:
以下是一个简单的 PHP 数据库留言板的示例代码:
CREATE TABLE messages (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
message TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);
// 检查连接
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
$name = $_POST['name'];
$message = $_POST['message'];
$sql = "INSERT INTO messages (name, message) VALUES ('$name', '$message')";
if ($conn->query($sql) === TRUE) {
echo "留言已提交";
} else {
echo "错误: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);
// 检查连接
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
$sql = "SELECT id, name, message, created_at FROM messages";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"]. " - Name: " . $row["name"]. " - Message: " . $row["message"]. " - Created at: " . $row["created_at"]. "<br>";
}
} else {
echo "没有留言";
}
$conn->close();
?>
$stmt = $conn->prepare("INSERT INTO messages (name, message) VALUES (?, ?)");
$stmt->bind_param("ss", $name, $message);
$stmt->execute();
$name = htmlspecialchars($_POST['name'], ENT_QUOTES, 'UTF-8');
$message = htmlspecialchars($_POST['message'], ENT_QUOTES, 'UTF-8');
领取专属 10元无门槛券
手把手带您无忧上云