Analysis of paging principle technical details (php + mysql) instances

Source: Internet
Author: User
The paging principle technical details analysis (php + mysql) instance mentions paging, which is familiar to everyone. we often encounter paging when browsing webpages, especially the list of news articles, as shown in:

Paging instance

Next, we will use an example to analyze the technical details of the paging principle.

I. functional development ideas

Before implementing the paging function, I first made a mind map to clarify the general idea ,:

Paging principle mind map

II. Introduction to function development modules

The tools used are lightweight editors.Editplus, Mysql database management toolPhpmyadmin, Environment isApache + PHP + Mysql in windows 7. Next, let's share with you how php and mysql can achieve the above paging effect.

1. Prepare for mysql database creation

When this function is designed, a database "fenye" is created, the table name is "people", the field -- serial number (id, as the primary key, auto-increment), name (name ), sex, for example:

Database "fenye" structure

2. Introduction to php functions

The php function page is designed with three public call Pages: conn. php, add. php on the information page, and list. php on the information list page. The following describes the technical details of each function page.

(1). public call page conn. php

This function page is used to connect databases and tables and set Database encoding. the code is as follows:

 

Annotation

  • @ Symbol is used to block mysql information displayed when an error occurs due to mysql connection failure. for user experience and security considerations;
  • Die () function: This function is used to throw an error message when the mysql database fails to connect. the content is customized.
(2) add. php

This function page mainly adds information records to the database. The core function code is to insert SQL statements,Complete CodeAs follows:

 Alert ('inserted successfully'); script ": mysql_error (); // triplicate statement. if the statement is executed successfully, a js script prompt is returned, the error mysql_error ()}?>

Add information

Annotation

  • Trielement judgment statement: condition? Result 1: Result 2: Successful execution result 1, failed execution result 2
  • The mysql_error () function is used to return text error messages generated by the previous mysql operation.
(3) list. php on the information list page

This page is mainly used to display the information List and implement the paging function.Complete Code, As follows:

Add information

Serial NumberNameGender $ Pagesize) {// if the total number of entries is greater than the number of entries displayed on each page, run the following paging code if ($ pageval <= 1) {// when the passed parameter 'page' is less than or equal to 1 (that is, the page number is not 0 or a negative value) $ pageval = 1; echo "$ num in total ". $ pagenum. "Last page on the next page";} else if ($ num/$ pagesize)-$ pageval) <= 0) {// total page number (not necessarily an integer) when the difference between the current page number and page number is less than or equal to 0, that is, the last page, run the following code echo "a total of $ num homepage previous pages ". $ pagenum;} else {// In other cases, that is, the page number is not the first or last page. run the following code echo "$ num homepage previous page ". $ pagenum. "Last page of the next page" ;}}$ SQL = "select * from 'people' limit $ page $ pagesize"; // query records based on the limit condition, Assign a value to $ SQL for the query statement $ query = mysql_query ($ SQL); // execute the code while ($ rs = mysql_fetch_array ($ query )) {// cyclically store each record as an array $ rs?>

Due to the long length of the code, we will analyze the details based on the functional implementation ideas below:First, find the core basis for function implementation. the core code of page number paging:Select * from 'table name' limit start value, number of reads;That is:

$sql="select * from `people` limit $page $pagesize";

Two variables need to be set, starting value$ Page, Read count$ Pagesize,$ PagesizeThe start value is a value that can be assigned to a user.$ PageIt will take some twists and turns to be used.Paging formula: Start Value = (current page-1) * number of entries per pageBecause we need to associate the current page number$ PagevalTo obtain the following code:

if($_GET["page"]){    $pageval=$_GET["page"];    $page=($pageval-1)*$pagesize;    $page.=",";}

Obtain$ PageThen, we need to implementHome page, previous page, next page, last page, page number, total number of recordsFunctions,Total number of recordsRelatively simple, directly query the number of all records$ NumThat is:

$numq=mysql_query("select * from `people"`);$num=mysql_num_rows($numq);

AsHomepage, previous page, next page, last page, and page numberThese parameters need to be used in the hyperlink to set the corresponding parameter '? Page = ', for example:

Format: Target page

So$ UrlAndCorresponding page numberYou need to find a way to obtain it. First, let's take a look at $ url acquisition. two functions are required:$ _ SERVER ["REQUEST_URI"](Used to obtain the complete URL ),Parse_url ()(Sort the url according to the components and store it as an array .)Path, That is:

$url=$_SERVER["REQUEST_URI"];$url=parse_url($url);$url=$url[path];

$ UrlAfter obtaining the information, let's take a look.Corresponding page number,HomepageThe simplest and most direct way to obtain parameters'Page = 1'You can,Previous and next pagesAre($ Pageval-1), ($ pageval + 1),Last pageIs'Page = total page', That is$ Sumpage. Here,Home page, last page, and intermediate pageConditional judgment is required:

  • Homepage: Current page$ PagevalWhen the value is less than or equal to 1;
  • Last page: When$ Num(Total number of items) and$ Pagesize(Number of items displayed per page) business and current page$ PagevalWhen the difference is less than or equal to 0 (that is, the quotient of the two is less than or equal to the current page value;
  • Intermediate page: Except for the above cases. That is
If ($ num> $ pagesize) {if ($ pagesize <= 1) {// Home Page $ pagesize = 1; echo "$ num page in total ". $ pagenum. "Last page of next page";} else if ($ num/$ pagesize)-$ pageval) <= 0) {// last page echo "previous page of $ num page ". $ pagenum;} else {// middle page echo "$ num page Home Page Previous Page ". $ pagenum. "Last page of the next page ";}}

WhereLast page'Page = $ sumpage' takes two values: when$ Num(Total number of items) and$ Pagesize(Number of entries displayed per page) when the operator is an integer,$ Sumpage = $ sum/$ pagesizeWhen the vendors of the two are not integers$ Sumpage = intval ($ sum/$ pagesize) + 1. That is

if(is_integer($sum/$pagesize)){    $sumpage=$sum/$pagesize;}else{    $sumpage=($sum/$pagesize)+1;}

Finally,$ Pagenum (page number list)It needs to be printed from the first page to the last page.For loopAnd make a conditional judgment: when the current page number is displayed, that is$ I ==$ pageval, Without hyperlink; in addition, add hyperlink, that is:

for($i=1;$i<=$sumpage;$++){    if($i==$pageval){      $pagenum.=$i." ";    }else{      $pagenum.="".$i."";    }}

Since then, the functional code segments of the entire paging function have been analyzed one by one. Based on this code, you can slightly modify and adjust the style to implement common and practical paging functions.

(4) summary

In fact, for every PHP learner,It is very important to lay a good foundation, so that we can avoid repeated mistakes in future studies, affecting the learning progress and depth,We recommend that you read PHP: PHP manual several times. In addition, we recommend a php repl: PsySH for you to experiment and Debug PHP code. I wish you all the best!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.