点赞功能是一种常见的Web应用交互功能,允许用户对内容(如文章、评论、图片等)表达喜欢或不喜欢的态度。在MySQL数据库中实现点赞功能,通常涉及以下几个基础概念:
CREATE TABLE Users (
user_id INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(255) NOT NULL
);
CREATE TABLE Contents (
content_id INT PRIMARY KEY AUTO_INCREMENT,
title VARCHAR(255) NOT NULL,
content TEXT
);
CREATE TABLE Likes (
like_id INT PRIMARY KEY AUTO_INCREMENT,
user_id INT,
content_id INT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES Users(user_id),
FOREIGN KEY (content_id) REFERENCES Contents(content_id)
);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>点赞功能</title>
</head>
<body>
<div id="content">
<h1>文章标题</h1>
<p>文章内容...</p>
<button id="likeButton">点赞</button>
<span id="likeCount">0</span>
</div>
<script>
document.getElementById('likeButton').addEventListener('click', function() {
fetch('/like', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ contentId: 1 }) // 假设内容ID为1
})
.then(response => response.json())
.then(data => {
document.getElementById('likeCount').textContent = data.likeCount;
});
});
</script>
</body>
</html>
const express = require('express');
const bodyParser = require('body-parser');
const mysql = require('mysql');
const app = express();
app.use(bodyParser.json());
const db = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password',
database: 'testdb'
});
db.connect(err => {
if (err) throw err;
console.log('Database connected!');
});
app.post('/like', (req, res) => {
const { contentId } = req.body;
const userId = 1; // 假设当前用户ID为1
db.query('SELECT * FROM Likes WHERE user_id = ? AND content_id = ?', [userId, contentId], (err, results) => {
if (err) throw err;
if (results.length > 0) {
// 用户已经点过赞,取消点赞
db.query('DELETE FROM Likes WHERE user_id = ? AND content_id = ?', [userId, contentId], (err, result) => {
if (err) throw err;
updateLikeCount(contentId, -1, res);
});
} else {
// 用户未点过赞,添加点赞记录
db.query('INSERT INTO Likes (user_id, content_id) VALUES (?, ?)', [userId, contentId], (err, result) => {
if (err) throw err;
updateLikeCount(contentId, 1, res);
});
}
});
});
function updateLikeCount(contentId, delta, res) {
db.query('UPDATE Contents SET like_count = like_count + ? WHERE content_id = ?', [delta, contentId], (err, result) => {
if (err) throw err;
db.query('SELECT like_count FROM Contents WHERE content_id = ?', [contentId], (err, results) => {
if (err) throw err;
res.json({ likeCount: results[0].like_count });
});
});
}
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
通过以上设计和实现,可以有效地在MySQL数据库中实现点赞功能,并处理常见的相关问题。
领取专属 10元无门槛券
手把手带您无忧上云