PHP是一种广泛使用的开源脚本语言,尤其适用于Web开发。MySQL是一个关系型数据库管理系统,用于存储和管理数据。留言板点赞功能通常是指用户可以对留言板上的帖子进行点赞,以表示喜欢或支持。
留言板点赞功能可以分为以下几种类型:
留言板点赞功能常见于各种社交网站、论坛、博客等,用户可以通过点赞来表达对内容的喜爱和支持。
以下是一个简单的PHP和MySQL实现留言板点赞功能的示例:
CREATE TABLE posts (
id INT AUTO_INCREMENT PRIMARY KEY,
content TEXT NOT NULL
);
CREATE TABLE likes (
id INT AUTO_INCREMENT PRIMARY KEY,
post_id INT NOT NULL,
user_id INT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (post_id) REFERENCES posts(id)
);
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";
// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);
// 检查连接
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
// 点赞功能
if (isset($_POST['like'])) {
$post_id = $_POST['post_id'];
$user_id = $_POST['user_id'];
// 检查是否已经点赞
$sql = "SELECT * FROM likes WHERE post_id = $post_id AND user_id = $user_id";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// 取消点赞
$sql = "DELETE FROM likes WHERE post_id = $post_id AND user_id = $user_id";
} else {
// 点赞
$sql = "INSERT INTO likes (post_id, user_id) VALUES ($post_id, $user_id)";
}
if ($conn->query($sql) === TRUE) {
echo "操作成功";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
// 获取点赞数
$post_id = 1; // 假设我们要获取ID为1的帖子的点赞数
$sql = "SELECT COUNT(*) as like_count FROM likes WHERE post_id = $post_id";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
echo "点赞数: " . $row["like_count"];
} else {
echo "0";
}
$conn->close();
?>
希望以上信息对你有所帮助!
领取专属 10元无门槛券
手把手带您无忧上云