Home  >  Article  >  Backend Development  >  How to use PHP to implement paging data loading in WeChat mini programs

How to use PHP to implement paging data loading in WeChat mini programs

PHPz
PHPzOriginal
2023-06-03 16:00:051297browse

With the popularity of WeChat mini programs, more and more developers are beginning to get involved. One of the common requirements is paginated data loading.

When implementing paging data loading in the WeChat applet, we can use PHP as the back-end language, use the MySQL database to store data, and use the interface provided by the WeChat applet to achieve data acquisition and display.

The following will introduce in detail how to use PHP to implement paging data loading of WeChat mini programs.

  1. Preparation work

Before we start writing code, we need to prepare the following tools and materials:

  • WeChat Mini Program Development Tools , used to create small program projects and perform page design and other operations.
  • PHP development environment can use integrated environments such as XAMPP or be built in a Linux system.
  • A MySQL database and create corresponding data tables in it.
  1. Create data table

Create a data table in the MySQL database to store data that needs to be displayed in pages. The structure of the data table should include the data fields that need to be displayed, as well as some additional fields for paging operations.

For example, if we want to display a product list, the structure of the data table may be as follows:

CREATE TABLE `goods` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `price` decimal(10,2) NOT NULL,
  `description` text NOT NULL,
  `image` varchar(255) NOT NULL,
  `created_at` datetime NOT NULL,
  `updated_at` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

In the above data table, the id field is an auto-increasing primary key, name stores the product name, price stores the product price, description stores the product description, image stores the product image address, created_at and updated_at are used to record the creation time and update time of data respectively.

  1. Write PHP code

Next, we need to write PHP code to handle the data request of the WeChat applet and return the data in pages.

In the PHP code, we need to first perform parameter verification to obtain the parameters passed by the front end of the mini program. Generally speaking, the applet needs to pass two parameters: the current page number and the number of records displayed on each page.

<?php
if (!isset($_GET['page'])) {
    die('参数错误:缺少page参数');
}
if (!isset($_GET['pagesize'])) {
    die('参数错误:缺少pagesize参数');
}

$page = max(intval($_GET['page']), 1);
$pageSize = intval($_GET['pagesize']);

In the above code, we use the intval() function to convert the string type parameter into an integer type, and use the max() function to ensure that the page number is not will be less than 1. If the parameters are missing or in the wrong format, the program will return an error message and end execution.

Next, we need to use the MySQL database query statement to obtain the data, and perform paging processing according to the page number and the number of records displayed on each page.

$offset = ($page - 1) * $pageSize;
$sql = 'SELECT * FROM goods ORDER BY created_at DESC LIMIT ' . $offset . ',' . $pageSize;
$result = $pdo->query($sql);
$goods = $result->fetchAll(PDO::FETCH_ASSOC);

In the above code, we use the LIMIT keyword to limit the number of returned query results, where the $offset variable represents the starting position of the current page, $pageSize represents the number of records displayed on each page.

Next, we need to convert the query results into JSON format and return it to the mini program front end.

header('Content-Type: application/json');
die(json_encode([
    'errno' => 0,
    'errmsg' => '',
    'data' => [
        'list' => $goods,
        'page' => $page,
        'pagesize' => $pageSize,
        'total' => $total,
    ],
]));

In the above code, we use the json_encode() function to convert the data into JSON format, and set the Content- of the response header through the header() function. Type to ensure that the mini program front-end can parse the returned data normally.

  1. Mini program front-end code

Finally, we need to call the PHP interface in the mini program front-end code to obtain paging data. Generally speaking, we can use the wx.request() function to initiate a network request and render the obtained data into the page.

Page({
  data: {
    goodsList: [],
    page: 1,
    pagesize: 10,
    total: 0,
  },
  onLoad: function () {
    this.loadGoodsList();
  },
  loadGoodsList: function () {
    wx.showLoading({
      title: '加载中',
    });
    wx.request({
      url: 'http://your.site.com/api/goods.php',
      data: {
        page: this.data.page,
        pagesize: this.data.pagesize,
      },
      success: (res) => {
        wx.hideLoading();
        const list = res.data.data.list || [];
        const page = res.data.data.page || 1;
        const pagesize = res.data.data.pagesize || 10;
        const total = res.data.data.total || 0;
        this.setData({
          goodsList: [...this.data.goodsList, ...list],
          page,
          pagesize,
          total,
        });
      },
      fail: (res) => {
        wx.hideLoading();
        wx.showToast({
          title: res.errmsg || '请求失败',
          icon: 'none',
        });
      },
    });
  },
  loadMoreGoods: function () {
    if (this.data.goodsList.length >= this.data.total) {
      return;
    }
    this.setData({
      page: this.data.page + 1,
    });
    this.loadGoodsList();
  },
});

In the above code, we define a loadMoreGoods() function to load more data. In this function, we determine whether we need to continue loading more data by comparing the number of records displayed in the current list with the total number of records.

When the user pulls up the list, we call the loadMoreGoods() function to obtain the data on the next page. After splicing the newly obtained data with the already displayed data, the page data is updated. .

  1. Summary

Through the above steps, we successfully implemented the function of paging data loading for WeChat mini programs using PHP. Through the introduction of the above code and principles, you should now have mastered the method of implementing paging loading.

Of course, this is just the most basic usage. In fact, in actual development, we also need to pay attention to some details, such as optimization of data caching, page rendering, etc. I hope the above content can provide some help for your WeChat applet development.

The above is the detailed content of How to use PHP to implement paging data loading in WeChat mini programs. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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