search
HomeBackend DevelopmentPHP Tutorial一个分页的问题:不能分页查询

代码写的比较乱  如果不想看代码只看我表述也行 然后提交解决的办法就行
代码是这样的 就是类似百度的一个搜索页 道理也是百度搜索这样的 有一个搜索框
 下面是一个div显示查询结果 比如我搜索PHP 然后就去表里面的num字段下查找PHP的内容 查询的所有结果以分页的形式展示出来 
就是第一页 第二页……   现在的问题是这个查询结果是根据用户每次提交时$_POST['num']来查询数据库的  
如果每页显示5条数据 现在查询出来3页数据 每次查询可以显示数据和分页信息  但是每次点击分页时就会报错 比如点击第二页时就是提示num未定义
因为点击第二页时没有提交的$_POST['num']数据 只有一个post过来的page=2 所以会报错 
 现在的问题就是只能查询第一页的数据  点第二页就会报错 知道问题出在哪里就是不知道怎么改  用户在点击第二页时希望之前查询出来的数据不要消失 这个应该怎么办呢?这样说不知道大家能不能看懂啊

<div id="show">       <?php       header('content-type:text/html;charset=utf-8;');       include 'function.php';       if (isset($_POST['num'])||isset($_GET['page'])) {       $pdo=new PDO("mysql:host=localhost;dbname=t1","root","");       session_start();       $_SESSION['num']=$_POST['num'];       $stmt3=$pdo->prepare("select * from table1 where num=?");       $stmt3->execute(array($_POST['num']));       $res3=$stmt3->fetchall();       $rows=count($res3);       $pagesize=5;       if($rows==0){        $pagenum=1;       }else{        $pagenum=ceil($rows/$pagesize);       }       if(isset($_GET['page'])){          $page=$_GET['page'];          if(empty($page)||$page<0||!is_numeric($page)) {            $page=1;          }else{            $page=intval($page);          }        }else{        $page=1;       }       if($page>$pagenum){        $page=$pagenum;       }       $startnum = ($page - 1)*$pagesize;       $display_page=5;       $query = "SELECT * FROM qq where num=? LIMIT $startnum,$pagesize";       $stmt=$pdo->prepare("$query");       //$stmt=$pdo->prepare("select * from table1 where num=?");       $stmt->execute(array($_POST['num']));       $res=$stmt->fetchall(PDO::FETCH_ASSOC);       $v = current($res);       if($res){         foreach($res as $v){          //echo '<h3 id="span-v-num-span"><span>'.$v['num'].'</span></h3>' ;          echo '<h4 id="v-name">'.$v['name'].'</h4>';         }       }else{        echo "无数据";       }               }       ?>     </div>     <div id="page">        <?php         if(isset($_POST['num'])||isset($_GET['page'])){           fenye();         }       ?>     </div>


回复讨论(解决方案)

你的 num 是 post 提交的,从第二页起就没有 post 提交了,自然也就没有了 num

因为你点第一页,第二页时,用的是GET方法传递,而不是POST方法。

所以红色部分出问题
       $query = "SELECT * FROM qq where num=? LIMIT $startnum,$pagesize";
       $stmt=$pdo->prepare("$query");
       //$stmt=$pdo->prepare("select * from table1 where num=?");
       $stmt->execute(array($_POST['num']));

然后fenye方法要把num和page传入去
分页的url要加上这两个参数:?page=xxx&num=xxx

这样改试试

<div id="show">       <?php       header('content-type:text/html;charset=utf-8;');       include 'function.php';       $num = isset($_REQUEST['num'])? $_REQUEST['num'] : 0;       $page = isset($_REQUEST['page'])? $_REQUEST['page'] : 1;        $pdo=new PDO("mysql:host=localhost;dbname=t1","root","");        session_start();        $_SESSION['num']=$num;        $stmt3=$pdo->prepare("select * from table1 where num=?");        $stmt3->execute(array($num));        $res3=$stmt3->fetchall();        $rows=count($res3);        $pagesize=5;        if($rows==0){            $pagenum=1;        }else{            $pagenum=ceil($rows/$pagesize);        }        if($page){            if(empty($page)||$page<0||!is_numeric($page)) {                $page=1;            }else{                $page=intval($page);            }         }else{            $page=1;        }        if($page>$pagenum){            $page=$pagenum;        }        $startnum = ($page - 1)*$pagesize;        $display_page=5;        $query = "SELECT * FROM qq where num=? LIMIT $startnum,$pagesize";        $stmt=$pdo->prepare("$query");        //$stmt=$pdo->prepare("select * from table1 where num=?");        $stmt->execute($num);        $res=$stmt->fetchall(PDO::FETCH_ASSOC);        $v = current($res);        if($res){            foreach($res as $v){                //echo '<h3 id="span-v-num-span"><span>'.$v['num'].'</span></h3>' ;                echo '<h4 id="v-name">'.$v['name'].'</h4>';            }        }else{         echo "无数据";        }       ?>     </div>     <div id="page">        <?php         if($num || $page){           fenye($num, $page);         }       ?>     </div>

你说像百度那样子,你就看看百度的下一页链接。搜索词都是在地址参数上的,用GET就行

还是不行  只是现在不报错了  点击第几页后还是什么都不显示内容


因为你点第一页,第二页时,用的是GET方]法传递,而不是POST方法。

所以红色部分出问题
       $query = "SELECT * FROM qq where num=? LIMIT $startnum,$pagesize";
       $stmt=$pdo->prepare("$query");
       //$stmt=$pdo->prepare("select * from table1 where num=?");
       $stmt->execute(array($_POST['num']));

然后fenye方法要把num和page传入去
分页的url要加上这两个参数:?page=xxx&num=xxx

这样改试试

<div id="show">       <?php       header('content-type:text/html;charset=utf-8;');       include 'function.php';       $num = isset($_REQUEST['num'])? $_REQUEST['num'] : 0;       $page = isset($_REQUEST['page'])? $_REQUEST['page'] : 1;        $pdo=new PDO("mysql:host=localhost;dbname=t1","root","");        session_start();        $_SESSION['num']=$num;        $stmt3=$pdo->prepare("select * from table1 where num=?");        $stmt3->execute(array($num));        $res3=$stmt3->fetchall();        $rows=count($res3);        $pagesize=5;        if($rows==0){            $pagenum=1;        }else{            $pagenum=ceil($rows/$pagesize);        }        if($page){            if(empty($page)||$page<0||!is_numeric($page)) {                $page=1;            }else{                $page=intval($page);            }         }else{            $page=1;        }        if($page>$pagenum){            $page=$pagenum;        }        $startnum = ($page - 1)*$pagesize;        $display_page=5;        $query = "SELECT * FROM qq where num=? LIMIT $startnum,$pagesize";        $stmt=$pdo->prepare("$query");        //$stmt=$pdo->prepare("select * from table1 where num=?");        $stmt->execute($num);        $res=$stmt->fetchall(PDO::FETCH_ASSOC);        $v = current($res);        if($res){            foreach($res as $v){                //echo '<h3 id="span-v-num-span"><span>'.$v['num'].'</span></h3>' ;                echo '<h4 id="v-name">'.$v['name'].'</h4>';            }        }else{         echo "无数据";        }       ?>     </div>     <div id="page">        <?php         if($num || $page){           fenye($num, $page);         }       ?>     </div>

就是啊  这个问题怎么解决呢?  

你的 num 是 post 提交的,从第二页起就没有 post 提交了,自然也就没有了 num

这个那个分页函数的代码
function fenye(){
global $page,$pagenum,$shoupage,$pageoffset;
echo "

";
echo "
    ";
    echo '
  • '.$page.'/'.$pagenum.'页|
  • ';
       if($page==1){
                 echo '
  • 首页|
  • ';
                 echo '
  • 上一页|
  • ';
       }else{
         echo '
  • 首页|
  • ';
                 echo '
  • 上一页|
  • ';
       }
       $shoupage=5;
           $pageoffset=($shoupage-1)/2;
           $start=1;
           $end=$pagenum;
       if($pagenum>$shoupage){
            if($page>$pageoffset){
            $start=$page-$pageoffset;
            $end=$pagenum>$page+$pageoffset?$page+$pageoffset:$pagenum;
            }else{
            $start=1;
            $end=$pagenum>$shoupage?$shoupage:$pagenum;
            }
            if($page+$pageoffset>$pagenum){
            $start=$start-($page+$pageoffset-$end);
            }
           }
       echo '
    ';
           echo '
      ';
             for($i=$start;$i         echo '
    • '.($i).'
    • ';
             }
             echo '
    ';
               echo '
    ';
       if($page==$pagenum){
        echo '
  • |下一页|
  • ';
        echo '
  • 尾页|
  • ';
       }else{
        echo '
  • |下一页|
  • ';
        echo '
  • 尾页|
  • ';
       }
    echo '
';
    echo '
';
    
};
?>

在链接中加入  num=$num

把原来这句话        echo '

  • '.($i).'
  • ';
    改成了这样echo '
  • '.($i).'
  • ';这样改对吗 但是还是提示我拼接错误  为什么?Parse error: syntax error, unexpected '=', expecting ',' or ';' in D:\wamp\www\function.php on line 33

    在链接中加入  num=$num

    改这样

    <?phpfunction fenye($num){global $page,$pagenum,$shoupage,$pageoffset;echo "<div >";echo "<ul id='ul2'>";echo '<li>'.$page.'/'.$pagenum.'页|</li>';   if($page==1){             echo '<li>首页|</li>';             echo '<li>上一页|</li>';   }else{     echo '<li><a href="'.$_SERVER["SCRIPT_NAME"].'">首页</a>|</li>';             echo '<li><a href="'.$_SERVER["SCRIPT_NAME"].'?'.($page-1).'&num='.$num.'">上一页</a>|</li>';   }   $shoupage=5;       $pageoffset=($shoupage-1)/2;       $start=1;       $end=$pagenum;   if($pagenum>$shoupage){        if($page>$pageoffset){        $start=$page-$pageoffset;        $end=$pagenum>$page+$pageoffset?$page+$pageoffset:$pagenum;        }else{        $start=1;        $end=$pagenum>$shoupage?$shoupage:$pagenum;        }        if($page+$pageoffset>$pagenum){        $start=$start-($page+$pageoffset-$end);        }       }   echo '<div>';       echo '<ul id="ul1">';       for($i=$start;$i<=$end;$i++){        echo '<li><a href="'.$_SERVER["SCRIPT_NAME"].'?page='.$i.'&num='.$num.'">'.($i).'</a></li>';       }       echo '</ul>';           echo '</div>';   if($page==$pagenum){    echo '<li>|下一页|</li>';    echo '<li>尾页|</li>';   }else{    echo '<li>|<a href="'.$_SERVER["SCRIPT_NAME"].'?page='.($page+1).'&num='.$num.'">下一页</a>|</li>';    echo '<li><a href="'.$_SERVER["SCRIPT_NAME"].'?page='.$pagenum.'&num='.$num.'">尾页</a>|</li>';   }echo '</ul>';    echo '</div>';    };?>


    然后调用改这样
         


                     if($num || $page){
               fenye($num);
             }
           ?>
         

    哈哈可以了  我先好好看看你的代码   

    改这样

    <?phpfunction fenye($num){global $page,$pagenum,$shoupage,$pageoffset;echo "<div >";echo "<ul id='ul2'>";echo '<li>'.$page.'/'.$pagenum.'页|</li>';   if($page==1){             echo '<li>首页|</li>';             echo '<li>上一页|</li>';   }else{     echo '<li><a href="'.$_SERVER["SCRIPT_NAME"].'">首页</a>|</li>';             echo '<li><a href="'.$_SERVER["SCRIPT_NAME"].'?'.($page-1).'&num='.$num.'">上一页</a>|</li>';   }   $shoupage=5;       $pageoffset=($shoupage-1)/2;       $start=1;       $end=$pagenum;   if($pagenum>$shoupage){        if($page>$pageoffset){        $start=$page-$pageoffset;        $end=$pagenum>$page+$pageoffset?$page+$pageoffset:$pagenum;        }else{        $start=1;        $end=$pagenum>$shoupage?$shoupage:$pagenum;        }        if($page+$pageoffset>$pagenum){        $start=$start-($page+$pageoffset-$end);        }       }   echo '<div>';       echo '<ul id="ul1">';       for($i=$start;$i<=$end;$i++){        echo '<li><a href="'.$_SERVER["SCRIPT_NAME"].'?page='.$i.'&num='.$num.'">'.($i).'</a></li>';       }       echo '</ul>';           echo '</div>';   if($page==$pagenum){    echo '<li>|下一页|</li>';    echo '<li>尾页|</li>';   }else{    echo '<li>|<a href="'.$_SERVER["SCRIPT_NAME"].'?page='.($page+1).'&num='.$num.'">下一页</a>|</li>';    echo '<li><a href="'.$_SERVER["SCRIPT_NAME"].'?page='.$pagenum.'&num='.$num.'">尾页</a>|</li>';   }echo '</ul>';    echo '</div>';    };?>


    然后调用改这样
         


                     if($num || $page){
               fenye($num);
             }
           ?>
         
    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 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

    How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

    TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

    PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

    ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

    PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

    Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

    PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

    DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

    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

    PhpStorm Mac version

    PhpStorm Mac version

    The latest (2018.2.1) professional PHP integrated development tool

    DVWA

    DVWA

    Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    SecLists

    SecLists

    SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

    Dreamweaver Mac version

    Dreamweaver Mac version

    Visual web development tools