PHP development practice: Use PHP and MySQL to implement article paging function
Introduction:
In website development, article paging is a common functional requirement. When there is too much article content, in order to make it easier for users to read, we need to divide the article into multiple pages and provide corresponding navigation functions. This article will introduce how to use PHP and MySQL to implement article paging function, and come with code examples.
SELECT COUNT(*) FROM articles;
In PHP, you can use MySQLi or PDO extension to connect to the database and execute the above SQL statement. The following is a sample code using the MySQLi extension:
<?php $servername = "localhost"; $username = "your_username"; $password = "your_password"; $dbname = "your_database"; // 创建连接 $conn = new mysqli($servername, $username, $password, $dbname); // 检查连接是否成功 if ($conn->connect_error) { die("连接失败: " . $conn->connect_error); } // 查询总文章数 $sql = "SELECT COUNT(*) AS total FROM articles"; $result = $conn->query($sql); $row = $result->fetch_assoc(); $totalArticles = $row["total"]; // 关闭连接 $conn->close(); ?>
总页数 = CEILING(总文章数 / 每页显示的文章数)
In PHP, this can be achieved using the ceil()
function Calculation of the above formula. The following is a sample code:
<?php $articlesPerPage = 10; $totalPages = ceil($totalArticles / $articlesPerPage); ?>
SELECT * FROM articles LIMIT 起始位置, 每页显示的文章数;
The starting position can be calculated by the following formula:
起始位置 = (当前页码 - 1) * 每页显示的文章数;
In PHP, you can use the following code to query the specified page Article:
<?php // 获取用户请求的页码 $page = isset($_GET['page']) ? $_GET['page'] : 1; // 计算起始位置 $start = ($page - 1) * $articlesPerPage; // 查询指定页的文章 $sql = "SELECT * FROM articles LIMIT $start, $articlesPerPage"; $result = $conn->query($sql); $articles = $result->fetch_all(MYSQLI_ASSOC); ?>
<a>
tag and passing page number information through URL parameters. The following is a sample code for displaying paginated navigation at the bottom of the page:
<?php $baseUrl = "http://yourwebsite.com/articles.php"; ?> <div class="pagination"> <?php for ($i = 1; $i <= $totalPages; $i++) { ?> <a href="<?php echo $baseUrl . '?page=' . $i; ?>"><?php echo $i; ?></a> <?php } ?> </div>
Conclusion:
Article pagination is a common and practical feature that can improve user experience and page loading speed. By using PHP and MySQL, we can easily implement article paging function. This article introduces the methods of using PHP and MySQL to query the total number of articles, calculate the total number of pages, query articles on a specified page and display paginated navigation, and provides relevant code examples. I hope this article will be helpful to readers who are learning and practicing PHP development.
The above is the detailed content of PHP development practice: using PHP and MySQL to implement article paging function. For more information, please follow other related articles on the PHP Chinese website!