PHP development: How to implement article reading statistics function, specific code examples are required
Introduction:
In the process of website or application development, it is often necessary to review articles Statistics of reading volume are conducted to understand user attention and article popularity. This article will introduce how to use PHP to develop and implement the article reading statistics function, and provide specific code examples.
CREATE TABLE articles ( id INT AUTO_INCREMENT, title VARCHAR(255), content TEXT, view_count INT DEFAULT 0, PRIMARY KEY (id) );
<?php // 获取文章ID $articleId = $_GET['id']; // 更新阅读量 $pdo = new PDO('mysql:host=localhost;dbname=your_database', 'your_username', 'your_password'); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $stmt = $pdo->prepare('UPDATE articles SET view_count = view_count + 1 WHERE id = :id'); $stmt->bindParam(':id', $articleId); $stmt->execute(); // 获取文章内容及阅读量 $stmt = $pdo->prepare('SELECT * FROM articles WHERE id = :id'); $stmt->bindParam(':id', $articleId); $stmt->execute(); $article = $stmt->fetch(PDO::FETCH_ASSOC); // 显示文章内容及阅读量 echo '<h1>'.$article['title'].'</h1>'; echo '<p>'.$article['content'].'</p>'; echo '<p>阅读量:'.$article['view_count'].'</p>'; ?>
$articleId = $_GET['id']; $pdo = new PDO('mysql:host=localhost;dbname=your_database', 'your_username', 'your_password'); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $stmt = $pdo->prepare('UPDATE articles SET view_count = view_count + 1 WHERE id = :id'); $stmt->bindParam(':id', $articleId); $stmt->execute();
This code will get the article ID and use the UPDATE statement to read the corresponding article. Add 1 to the quantity field.
$articleId = $_GET['id']; $pdo = new PDO('mysql:host=localhost;dbname=your_database', 'your_username', 'your_password'); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $stmt = $pdo->prepare('SELECT * FROM articles WHERE id = :id'); $stmt->bindParam(':id', $articleId); $stmt->execute(); $article = $stmt->fetch(PDO::FETCH_ASSOC); echo '<h1>'.$article['title'].'</h1>'; echo '<p>'.$article['content'].'</p>'; echo '<p>阅读量:'.$article['view_count'].'</p>';
Through the above code, we can display the reading volume of the article on the article page.
Conclusion:
This article introduces how to use PHP to develop and implement the article reading statistics function, and provides specific code examples. By creating database tables, updating readings, and displaying readings, we can easily count the readings of articles. I hope this article will be helpful to you in implementing the article reading statistics function in the PHP development process.
The above is the detailed content of PHP development: How to implement article reading statistics function. For more information, please follow other related articles on the PHP Chinese website!