Home Backend Development PHP Tutorial How to use PHP to develop a simple data paging function

How to use PHP to develop a simple data paging function

Sep 25, 2023 am 08:11 AM
php development use Simple data paging

How to use PHP to develop a simple data paging function

How to use PHP to develop a simple data paging function

Introduction:
In website development, we often encounter situations where a large amount of data needs to be displayed in paging. In this case, you need to use the data paging function. This article will introduce how to use PHP to develop a simple data paging function and provide specific code examples.

1. Preparation work:
Before you start writing code, you need to prepare a database and a data table to store the data that needs to be displayed in pages. Taking the MySQL database as an example, create a data table named "users" with the following table structure:

CREATE TABLE users (
id int (11) NOT NULL AUTO_INCREMENT,
name varchar(50) NOT NULL,
age int(11) NOT NULL,
PRIMARY KEY ( id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

2. Write the paging function code:

  1. Connect to the database:
    First you need to create a connection function to the database and fill in the correct database connection information in the function. The code example is as follows:

function connectDB() {

$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "database";

// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);
// 检测连接是否成功
if ($conn->connect_error) {
    die("连接失败: " . $conn->connect_error);
}
return $conn;
Copy after login

}
?>

  1. Get data Total number:
    Next, you need to write a function to get the total number of records in the data table. The code example is as follows:

function getTotalCount() {

$conn = connectDB();
$sql = "SELECT COUNT(*) AS count FROM users";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
$count = $row["count"];
$conn->close();
return $count;
Copy after login

}
?>

  1. Paging query Data:
    Next, you need to write a function to query the corresponding data based on the page number and the number of records displayed on each page. The code example is as follows:

function getData($page, $pageSize) {

$conn = connectDB();
$start = ($page - 1) * $pageSize;
$sql = "SELECT * FROM users LIMIT $start, $pageSize";
$result = $conn->query($sql);
$data = array();
if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $data[] = $row;
    }
}
$conn->close();
return $data;
Copy after login

}
?>

  1. Display paging navigation:
    Finally, you need to write a function to display paging navigation to facilitate users to switch between different page numbers. The code example is as follows:

function showPagination($page, $pageSize, $totalCount) {

$totalPage = ceil($totalCount / $pageSize);
$prevPage = $page - 1;
$nextPage = $page + 1;

echo "<div class='pagination'>";
if ($page > 1) {
    echo "<a href='?page=$prevPage'>上一页</a>";
}
for ($i = 1; $i <= $totalPage; $i++) {
    if ($i == $page) {
        echo "<span class='current'>$i</span>";
    } else {
        echo "<a href='?page=$i'>$i</a>";
    }
}
if ($page < $totalPage) {
    echo "<a href='?page=$nextPage'>下一页</a>";
}
echo "</div>";
Copy after login

}
?>

3. Use the paging function:
Integrate the above function code into a PHP file, and add the following code to the file to display the paging function:

$page = isset($_GET['page']) ? $_GET['page'] : 1;
$pageSize = 10;

$totalCount = getTotalCount();
$data = getData($page, $pageSize);

// Display data
foreach ($data as $row) {

echo sprintf("ID:%s,姓名:%s,年龄:%s<br>", $row['id'], $row['name'], $row['age']);
Copy after login

}

// Display paging Navigation
showPagination($page, $pageSize, $totalCount);
?>

By accessing the PHP file, you can see the data displayed in paging and the paging navigation.

Conclusion:
Through the above steps, we successfully developed a simple data paging function using PHP and gave specific code examples. Readers can modify and expand the code according to actual needs to achieve more complex data paging functions. I hope this article can provide some reference and help for everyone to use the data paging function in website development.

The above is the detailed content of How to use PHP to develop a simple data paging function. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use Memcache in PHP development? How to use Memcache in PHP development? Nov 07, 2023 pm 12:49 PM

In web development, we often need to use caching technology to improve website performance and response speed. Memcache is a popular caching technology that can cache any data type and supports high concurrency and high availability. This article will introduce how to use Memcache in PHP development and provide specific code examples. 1. Install Memcache To use Memcache, we first need to install the Memcache extension on the server. In CentOS operating system, you can use the following command

What does TikTok recommended video mean? How to use Douyin to recommend videos? What does TikTok recommended video mean? How to use Douyin to recommend videos? Mar 27, 2024 pm 03:01 PM

As a world-renowned short video social platform, Douyin has won the favor of a large number of users with its unique personalized recommendation algorithm. This article will delve into the value and principles of Douyin video recommendation to help readers better understand and make full use of this feature. 1. What is Douyin recommended video? Douyin recommended video uses intelligent recommendation algorithms to filter and push personalized video content to users based on their interests and behavioral habits. The Douyin platform analyzes users' viewing history, like and comment behavior, sharing records and other data to select and recommend videos that best suit users' tastes from a huge video library. This personalized recommendation system not only improves user experience, but also helps users discover more video content that matches their preferences, thereby enhancing user stickiness and retention rate. at this

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to use PHP to develop an online tutoring service platform How to use PHP to develop an online tutoring service platform Oct 28, 2023 am 09:01 AM

How to use PHP to develop an online tutoring service platform. With the rapid development of the Internet, online tutoring service platforms have attracted more and more people's attention and demand. Parents and students can easily find suitable tutors through such a platform, and tutors can also better demonstrate their teaching abilities and advantages. This article will introduce how to use PHP to develop an online tutoring service platform. First, we need to clarify the functional requirements of the platform. An online tutoring service platform needs to have the following basic functions: Registration and login system: users can

How to implement version control and code collaboration in PHP development? How to implement version control and code collaboration in PHP development? Nov 02, 2023 pm 01:35 PM

How to implement version control and code collaboration in PHP development? With the rapid development of the Internet and the software industry, version control and code collaboration in software development have become increasingly important. Whether you are an independent developer or a team developing, you need an effective version control system to manage code changes and collaborate. In PHP development, there are several commonly used version control systems to choose from, such as Git and SVN. This article will introduce how to use these tools for version control and code collaboration in PHP development. The first step is to choose the one that suits you

How to use PHP to develop the coupon function of the ordering system? How to use PHP to develop the coupon function of the ordering system? Nov 01, 2023 pm 04:41 PM

How to use PHP to develop the coupon function of the ordering system? With the rapid development of modern society, people's life pace is getting faster and faster, and more and more people choose to eat out. The emergence of the ordering system has greatly improved the efficiency and convenience of customers' ordering. As a marketing tool to attract customers, the coupon function is also widely used in various ordering systems. So how to use PHP to develop the coupon function of the ordering system? 1. Database design First, we need to design a database to store coupon-related data. It is recommended to create two tables: one

How to use PHP to develop the member points function of the grocery shopping system? How to use PHP to develop the member points function of the grocery shopping system? Nov 01, 2023 am 10:30 AM

How to use PHP to develop the member points function of the grocery shopping system? With the rise of e-commerce, more and more people choose to purchase daily necessities online, including grocery shopping. The grocery shopping system has become the first choice for many people, and one of its important features is the membership points system. The membership points system can attract users and increase their loyalty, while also providing users with an additional shopping experience. In this article, we will discuss how to use PHP to develop the membership points function of the grocery shopping system. First, we need to create a membership table to store users

What is the method to implement the takeout order tracking function of PHP development ordering system? What is the method to implement the takeout order tracking function of PHP development ordering system? Nov 01, 2023 am 08:58 AM

With the booming takeout business, major restaurants and takeout platforms are competing to launch ordering systems. The takeout order tracking function has become a feature that both customers and restaurants are paying close attention to. So, how do we implement the takeout order tracking function in the ordering system developed in PHP? 1. Front-end page design First, we need to design a front-end page so that users can easily check the order status. The following points need to be noted in the design of the front-end page: the interface is simple and clear, and users can quickly find the entrance to the order tracking function. In the process of order tracking

See all articles