以下是一个基本的PHP7留言板的评论功能的示例代码:
index.php:
<?php
// 连接数据库
$db_host = 'localhost';
$db_name = 'message_board';
$db_user = 'root';
$db_password = '';
$conn = new PDO("mysql:host=$db_host;dbname=$db_name;charset=utf8", $db_user, $db_password);
// 提交评论
if(isset($_POST['submit'])){
$name = $_POST['name'];
$comment = $_POST['comment'];
$stmt = $conn->prepare("INSERT INTO comments (name, comment) VALUES (:name, :comment)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':comment', $comment);
$stmt->execute();
}
// 获取评论列表
$stmt = $conn->prepare("SELECT * FROM comments ORDER BY id DESC");
$stmt->execute();
$comments = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html>
<head>
<title>留言板</title>
</head>
<body>
<h1>留言板</h1>
<form method="post" action="">
<label for="name">姓名:</label>
<input type="text" name="name" id="name" required><br>
<label for="comment">评论:</label>
<textarea name="comment" id="comment" required></textarea><br>
<input type="submit" name="submit" value="提交">
</form>
<h2>评论列表</h2>
<?php foreach($comments as $comment): ?>
<div>
<h3><?php echo $comment['name']; ?></h3>
<p><?php echo $comment['comment']; ?></p>
</div>
<?php endforeach; ?>
</body>
</html>
在上述代码中,我们首先连接到数据库,然后在提交评论时将评论存储到数据库中。然后,我们从数据库中获取评论列表并将其显示在页面上。用户可以在表单中输入姓名和评论,并点击提交按钮将评论提交到数据库中。
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站