Home > Article > Backend Development > PHP Practical Tutorial: Build a Complete Like System for Multiple Articles
In Web development, the like system is a very common function. Through likes, you can Allow users to express their love and support for the content. In this tutorial, we will use PHP to build a complete like system for multiple articles, allowing users to like operations on different articles.
Before building the like system, let’s first analyze the system requirements:
First, we need to design a database table to store article information and like records. The following are the two tables we need:
CREATE TABLE articles( id INT PRIMARY KEY AUTO_INCREMENT, title VARCHAR(255) NOT NULL, content TEXT NOT NULL, likes INT DEFAULT 0 );
CREATE TABLE likes( id INT PRIMARY KEY AUTO_INCREMENT, article_id INT, user_id INT );
Next, we will implement the page display part . We need an article list page where users can see all articles and like the articles.
<?php // 连接数据库 $conn = new mysqli("localhost", "username", "password", "database"); // 查询所有文章 $query = "SELECT * FROM articles"; $result = $conn->query($query); // 显示文章列表 while ($row = $result->fetch_assoc()) { echo "<h2>".$row['title']."</h2>"; echo "<p>".$row['content']."</p>"; echo "<p>Likes: ".$row['likes']."</p>"; echo "<form method='post' action='like.php'>"; echo "<input type='hidden' name='article_id' value='".$row['id']."'>"; echo "<button type='submit'>Like</button>"; echo "</form>"; } $conn->close(); ?>
<?php // 连接数据库 $conn = new mysqli("localhost", "username", "password", "database"); // 获取文章id $article_id = $_POST['article_id']; // 检查用户是否已经点赞过该文章(此处省略了用户验证部分) // 更新文章点赞数 $query = "UPDATE articles SET likes = likes + 1 WHERE id = $article_id"; $conn->query($query); // 记录点赞记录 $query = "INSERT INTO likes (article_id, user_id) VALUES ($article_id, $user_id)"; $conn->query($query); $conn->close(); header('Location: index.php'); ?>
Through the above steps, we have implemented a simple multi-article like system . When a user clicks the like button on the article list page, the system will update the number of likes for the article and record the like information, ensuring that the user can only like the same article once, while ensuring the accuracy and consistency of the number of likes.
Of course, this is just a simple example, and more functions and optimizations may be needed in actual applications, such as user authentication, like cancellation function, etc. I hope this tutorial can help you build a more powerful and complete like system in actual projects.
The above is the detailed content of PHP Practical Tutorial: Build a Complete Like System for Multiple Articles. For more information, please follow other related articles on the PHP Chinese website!