search
HomeBackend DevelopmentPHP Tutorialphp自动适应范围的分页代码_php技巧

复制代码 代码如下:

function page($page,$total,$phpfile,$pagesize=10,$pagelen=7){
    $pagecode = '';//定义变量,存放分页生成的HTML
    $page = intval($page);//避免非数字页码
    $total = intval($total);//保证总记录数值类型正确
    if(!$total) return array();//总记录数为零返回空数组
    $pages = ceil($total/$pagesize);//计算总分页
    //处理页码合法性
    if($page    if($page>$pages) $page = $pages;
    //计算查询偏移量
    $offset = $pagesize*($page-1);
    //页码范围计算
    $init = 1;//起始页码数
    $max = $pages;//结束页码数
    $pagelen = ($pagelen%2)?$pagelen:$pagelen+1;//页码个数
    $pageoffset = ($pagelen-1)/2;//页码个数左右偏移量

    //生成html
    $pagecode='
';
    $pagecode.="$page/$pages";//第几页,共几页
    //如果是第一页,则不显示第一页和上一页的连接
    if($page!=1){
        $pagecode.="";//第一页
        $pagecode.="
";//上一页
    }
    //分页数大于页码个数时可以偏移
    if($pages>$pagelen){
        //如果当前页小于等于左偏移
        if($page            $init=1;
            $max = $pagelen;
        }else{//如果当前页大于左偏移
            //如果当前页码右偏移超出最大分页数
            if($page+$pageoffset>=$pages+1){
                $init = $pages-$pagelen+1;
            }else{
                //左右偏移都存在时的计算
                $init = $page-$pageoffset;
                $max = $page+$pageoffset;
            }
        }
    }
    //生成html
    for($i=$init;$i        if($i==$page){
            $pagecode.=''.$i.'';
        } else {
            $pagecode.="
$i";
        }
    }
    if($page!=$pages){
        $pagecode.=">";//下一页
        $pagecode.=">>";//最后一页
    }
    $pagecode.="
";
    return array('pagecode'=>$pagecode,'sqllimit'=>' limit '.$offset.','.$pagesize);
}
?>

加了页码跳转文本框
以下是新手使用说明
复制代码 代码如下:

$phpfile = 'index.php';//页面文件名
$page= isset($_GET['page'])?$_GET['page']:1;//默认页码
$db = mysql_connect('localhost','test','test');//链接数据库
mysql_select_db('test',$db);//选择数据库
$counts = mysql_num_rows(mysql_query('select `id` from `test`',$db));//获取需要的数据总条数
$sql='select `id`,`title` from `test`';//定义查询语句SQL
$getpageinfo = page($page,$counts,$phpfile);//调用函数,生成分页HTML 和 SQL LIMIT 子句
$sql.=$getpageinfo['sqllimit'];//组合完整的SQL语句
$data = $row = array();//初始化数组
$result = mysql_query($sql,$db);//获取结果集
//将数据装入$data数组
while($row = mysql_fetch_array($result)){
     $data[]=$row;
}
?>
echo $getpageinfo['pagecode'];//显示分页的html代码
?>

======================
补贴css
复制代码 代码如下:


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.