能否提供一份用于实现PHP愿望墙功能的详细代码示例?
时间: 2024-12-26 07:28:47 浏览: 7
当然可以。PHP愿望墙功能通常是一个简单的网站应用程序,允许用户提交和查看其他人发布的愿望。这里是一个简化的例子,使用PHP、MySQL和HTML来创建一个基本的愿望墙:
```php
<?php
// 连接到数据库
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "wishes";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// 用户提交新愿望
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$wish = $_POST['wish'];
$sql = "INSERT INTO wishes (wish) VALUES ('$wish')";
if ($conn->query($sql) === TRUE) {
echo "新愿望已添加到墙上!";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
// 显示所有愿望
$sql = "SELECT * FROM wishes";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"]. " - 愿望: " . $row["wish"]. "<br>";
}
} else {
echo "目前还没有任何愿望!";
}
$conn->close();
?>
<!-- HTML表单 -->
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>愿望墙</title>
</head>
<body>
<form method="post" action="">
<label for="wish">写下你的愿望:</label><br>
<input type="text" id="wish" name="wish"><br>
<input type="submit" value="发布">
</form>
<hr>
<?php include 'display_wishes.php'; ?>
</body>
</html>
阅读全文