我遇到了一个问题,我正在进行一个查询,它回来了大约30页,我希望它能以1,2,3 ...而不是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> ");
}
echo "<br/><br/>";
}
sqlsrv_close( $conn );
答案 0 :(得分:0)
我接受了Code Review,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> ");
}
//If you always want to render current page number
else if($i == $pageNum) {
//render link
$pageLink = "?pageNum=$i";
print("<a href=$pageLink>$i</a> ");
//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> ");
}
//make sure you only do this once per ellipses group
else {
if (!$renderedEllipses){
print("...");
$renderedEllipses = true;
}
}
}
谢谢@ JohnMark13