search
HomeBackend DevelopmentPHP TutorialPHP paging program implementation code for PHP development_PHP tutorial

PHP paging program implementation code for PHP development_PHP tutorial

Jul 13, 2016 pm 04:55 PM
phpphp+mysqlcodePaginationexistaccomplishopenrelativelyprogramSimpleObtainwant

It is relatively simple to implement paging in php+mysql. Just get the page and then For reference.

Project structure:

Operation effect:

Database connection code

The code is as follows Copy code
 代码如下 复制代码

$conn = @ mysql_connect("localhost", "root", "") or die("数据库链接错误"); mysql_select_db("form", $conn);
mysql_query("set names 'GBK'"); //使用GBK中文编码;
//替换空格,回车键
function htmtocode($content)
{
$content = str_replace("n", "
", str_replace(" ", " ", $content));
return $content;
}
?>

$conn = @ mysql_connect("localhost", "root", "") or die("Database link error"); mysql_select_db("form", $conn);
mysql_query("set names 'GBK'"); //Use GBK Chinese encoding;
//Replace spaces and enter key
function htmtocode($content)
{
$content = str_replace("n", "
", str_replace(" ", " ", $content));
return $content;
}
?>

Here is a more important sharing core function

The code is as follows Copy code


Function _PAGEFT($totle, $displaypg = 20, $url = '') {

global $page, $firstcount, $pagenav, $_SERVER;

            $GLOBALS["displaypg"] = $displaypg;

          if (!$page)
$page = 1;
             if (!$url) {
               $url = $_SERVER["REQUEST_URI"];
         }

//URL analysis:
            $parse_url = parse_url($url);
          $url_query = $parse_url["query"]; //Get the query string of the URL separately
             if ($url_query) {
                $url_query = ereg_replace("(^|&)page=$page", "", $url_query);
                $url = str_replace($parse_url["query"], $url_query, $url);
                 if ($url_query)
                           $url .= "&page";
            else
                       $url .= "page";
          } else {
                  $url .= "?page";
         }
​​​​​ $lastpg = ceil($totle / $displaypg); //The last page, also the total number of pages
           $page = min($lastpg, $page);
$prepg = $page -1; //Previous page
          $nextpg = ($page == $lastpg ? 0 : $page +1); //Next page
         $firstcount = ($page -1) * $displaypg;

//Start paging navigation bar code:
$pagenav = "Display number " . ($totle ? ($firstcount +1) : 0) . "-" . min($firstcount + $displaypg, $totle) . " records, $totle records in total";

//If there is only one page, jump out of the function:
If ($lastpg               return false;

               $pagenav .= " Homepage ";
            if ($prepg)
                 $pagenav .= " Previous page ";
        else
                $pagenav .= "Previous page";
            if ($nextpg)
                  $pagenav .= " Next page ";
        else
                 $pagenav .= "Next page";
             $pagenav .= " Last page ";

//Pull down the jump list and list all page numbers in a loop:
             $pagenav .= "Go to page page of $lastpg";
}


include("conn.php");

$result=mysql_query("SELECT * FROM `test`");
$total=mysql_num_rows($result);
//Call pageft() to display 10 pieces of information per page (this parameter can be omitted when using the default 20), and use the URL of this page (default, so omit it).
_PAGEFT($total,5);
echo $pagenav;

$result=mysql_query("SELECT * FROM `test` limit $firstcount,$displaypg ");
while($row=mysql_fetch_array($result)){

echo "


".$row[name]." | ".$row[sex];

}
?>

list.php

Database query records and generate sql query statements

The code is as follows
 代码如下 复制代码
include("conn.php");
$pagesize=5; 5 $url=$_SERVER["REQUEST_URI"];
$url=parse_url($url);
$url=$url[path];
$numq=mysql_query("SELECT * FROM `test`");
$num = mysql_num_rows($numq);
if($_GET[page]){
$pageval=$_GET[page];
$page=($pageval-1)*$pagesize;
$page.=',';
}
if($num > $pagesize){
if($pageval echo "共 $num 条". 21 " 上一页 下一页";
}
$SQL="SELECT * FROM `test` limit $page $pagesize ";
$query=mysql_query($SQL);
while($row=mysql_fetch_array($query)){
echo "
".$row[name]." | ".$row[sex];
}
 ?>
Copy code
include("conn.php"); $pagesize=5; 5 $url=$_SERVER["REQUEST_URI"]; $url=parse_url($url); $url=$url[path]; $numq=mysql_query("SELECT * FROM `test`"); $num = mysql_num_rows($numq); if($_GET[page]){ $pageval=$_GET[page]; $page=($pageval-1)*$pagesize; $page.=','; } if($num > $pagesize){ if($pageval echo "Total $num items". 21 " Previous page Next page"; } $SQL="SELECT * FROM `test` limit $page $pagesize "; $query=mysql_query($SQL); while($row=mysql_fetch_array($query)){ echo "
".$row[name]." | ".$row[sex]; } ?>

Paging formula: (current page number - 1) * number of items per page, number of items per page

 代码如下 复制代码
sql语句:select * from test_table limit ($page-1)*$pageSize,$pageSize;

Summary:

No matter what program is developed, it is divided into one. The original method is to take N items starting from Take 5 out of 1.

Let’s introduce the core code. Here we get the paging number, and the Xpagesize code is as follows

 代码如下 复制代码
if($_GET[page]){
$pageval=$_GET[page];
$page=($pageval-1)*$pagesize;
$page.=',';
}
if($num > $pagesize){
if($pageval


It is relatively easy to divide in mysql+php because of limit

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/631629.htmlTechArticleIt is relatively simple to implement paging in php+mysql. Just get the page and then Paging can be perfectly realized by using limit n, M. This example clearly explains the need...
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
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

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 Article

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.