PHP连接MSSQL分页功能异常:无法跳转至其他页码
分页失效问题修复方案
核心问题
你的分页点击后不跳转,是因为代码里强制将$Page变量固定为1,完全忽略了URL传递的Page参数:
{ $Page=1; }
这段代码会覆盖所有从URL传入的页码值,导致无论点击哪个分页链接,页面始终停在第1页。
完整修复代码
<html> <head> <title>ShotDev.Com Tutorial</title> </head> <body> <?php $sql_name = 'test'; $sql_user = 'sa'; $sql_pass = ''; $dbConn = odbc_connect("Driver={SQL Server};Server={$sql_name};",$sql_user,$sql_pass) or die('Database Connection Error!'); if (!$dbConn) { exit("Connection failed:".odbc_errormsg()); } $Per_Page = 22; // 每页显示条数 // 1. 统计总记录数(优化原遍历计数的低效方式) $countSql = "SELECT COUNT(*) AS total FROM test_db.dbo.test"; $countResult = odbc_exec($dbConn, $countSql) or die("Error counting records: ".odbc_errormsg()); odbc_fetch_row($countResult); $Num_Rows = (int)odbc_result($countResult, 'total'); // 2. 计算总页数 if($Num_Rows <= $Per_Page) { $Num_Pages = 1; } else if(($Num_Rows % $Per_Page) == 0) { $Num_Pages = $Num_Rows / $Per_Page; } else { $Num_Pages = (int)($Num_Rows / $Per_Page) + 1; } // 3. 处理页码参数:从URL获取,默认1,做边界校验 $Page = isset($_GET['Page']) && is_numeric($_GET['Page']) ? (int)$_GET['Page'] : 1; $Page = max(1, min($Page, $Num_Pages)); // 确保页码在合法范围内 $Prev_Page = $Page - 1; $Next_Page = $Page + 1; // 4. 执行分页查询(MSSQL 2005+支持ROW_NUMBER(),高效分页) $offset = ($Page - 1) * $Per_Page; $strSQL = "WITH PaginatedData AS ( SELECT *, ROW_NUMBER() OVER (ORDER BY ID ASC) AS RowNum FROM test_db.dbo.test ) SELECT * FROM PaginatedData WHERE RowNum > $offset AND RowNum <= $offset + $Per_Page"; $objExec = odbc_exec($dbConn, $strSQL) or die ("Error Execute [".$strSQL."]"); ?> <table width="600" border="1"> <tr> <th width="91"> <div align="center">ID </div></th> <th width="98"> <div align="center">Name </div></th> </tr> <?php // 直接遍历分页结果集,替代原按行号截取的方式 while($objResult = odbc_fetch_array($objExec)) { ?> <tr> <td><div align="center"><?=$objResult["ID"];?></div></td> <td><?=$objResult["Name"];?></td> </tr> <?php } ?> </table> <br> Total <?php echo $Num_Rows;?> Record : <?php echo $Num_Pages;?> Page : <?php if($Prev_Page >= 1) { echo " <a href='$_SERVER[SCRIPT_NAME]?Page=$Prev_Page'><< Back</a> "; } for($i=1; $i<=$Num_Pages; $i++){ if($i != $Page) { echo "[ <a href='$_SERVER[SCRIPT_NAME]?Page=$i'>$i</a> ]"; } else { echo "<b> $i </b>"; } } if($Page < $Num_Pages) { echo " <a href ='$_SERVER[SCRIPT_NAME]?Page=$Next_Page'>Next>></a> "; } odbc_close($dbConn); ?> </body> </html>
关键优化点
- 修复页码逻辑:从URL获取
Page参数,同时做数字校验和边界限制,避免非法页码 - 高效统计总数:用SQL直接统计总记录数,替代遍历所有结果的低效方式
- 高效分页查询:使用MSSQL的
ROW_NUMBER()函数实现分页,只查询当前页数据,减少数据库负载 - 简化结果遍历:直接遍历分页后的结果集,避免原代码中结果集指针偏移的问题
内容的提问来源于stack exchange,提问作者Codename007
相关产品推荐
相关产品推荐

