0

我在进行查询时遇到问题,它返回大约 30 页,我希望它返回 1,2,3...,30 而不是 1,2,3,4, 5、6、7、8等 请参阅下面的代码,了解我使用过的代码:

function getPage($stmt, $pageNum, $rowsPerPage)
{
$offset = ($pageNum - 1) * $rowsPerPage;
$rows = array();
$i = 0;
while(($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_NUMERIC, 
     SQLSRV_SCROLL_ABSOLUTE,         $offset + $i)) && $i < $rowsPerPage)
{
    array_push($rows, $row);
    $i++;
}
return $rows;
}

// Set the number of rows to be returned on a page.
$rowsPerPage = 30;

// Connect to the server.
$serverName = 'test';
$connOptions = array("Database"=>"test");
$conn = sqlsrv_connect($serverName, $connOptions);
if (!$conn)
die( print_r( sqlsrv_errors(), true));

//  Define and execute the query.  
// Note that the query is executed with a "scrollable" cursor.
$sql = "select * from info";

$stmt = sqlsrv_query($conn, $sql, array(), array( "Scrollable" => 'static' ));
if ( !$stmt )
die( print_r( sqlsrv_errors(), true));

// Display the selected page of data.
echo "<table border='1px' align='center'>";
$pageNum = isset($_GET['pageNum']) ? $_GET['pageNum'] : 1;
$page = getPage($stmt, $pageNum, $rowsPerPage);

foreach($page as $row)
echo "<tr><td>$row[0]</td><td>$row[1]</td><td>$row[2]</td><td>$row[3]</td></tr>";

echo "</table>";
?>
<table align='center'>
<?php
// Get the total number of rows returned by the query.
// Display links to "pages" of rows.
$rowsReturned = sqlsrv_num_rows($stmt);
if($rowsReturned === false)
die( print_r( sqlsrv_errors(), true));
elseif($rowsReturned == 0)
{
echo "No rows returned.";
exit();
}
else
{     
// Display page links.
$numOfPages = ceil($rowsReturned/$rowsPerPage);
for($i = 1; $i<=$numOfPages; $i++)
{
    $pageLink = "?pageNum=$i";
    print("<a href=$pageLink>$i</a>&nbsp;&nbsp;");
}
echo "<br/><br/>";
} 



sqlsrv_close( $conn );
4

1 回答 1

0

我进行了代码审查,JohnMark13 帮助我找到了解决这个问题的方法:

// Display page links.
$numOfPages = ceil($rowsReturned/$rowsPerPage);
$renderedEllipses = false;
for($i = 1; $i<=$numOfPages; $i++)
{
    //If you always want to render pages 1 - 3
    if($i < 4) {
        //render link
        $pageLink = "?pageNum=$i";
        print("<a href=$pageLink>$i</a>&nbsp;&nbsp;");
    }

    //If you always want to render current page number
    else if($i == $pageNum) {
        //render link
        $pageLink = "?pageNum=$i";
        print("<a href=$pageLink>$i</a>&nbsp;&nbsp;");
        //reset ellipses
        $renderedEllipses = false;
    }

    //if you always want the last page number
    else if ($i == $numOfPages - 1) {
        //render link
        $pageLink = "?pageNum=$i";
        print("<a href=$pageLink>$i</a>&nbsp;&nbsp;");
    }

    //make sure you only do this once per ellipses group
    else {
         if (!$renderedEllipses){
             print("...");
             $renderedEllipses = true;
         }
     }
}

谢谢@JohnMark13

于 2013-09-04T19:33:21.230 回答