我花了好几天时间努力完成这项工作。我有一个图书数据库。我有一个名为getBooks的函数文件。
function getBooks($limit = 10000, $sortBy = 'tblAuthor.LastName' , $direction='ASC', $where=1){
$db = connect();
$fields = array('tblBook.Title', 'tblAuthor.FirstName', 'tblAuthor.LastName', 'tblCategory.Category');
$format = 'Select '. implode(', ', $fields) .' FROM tblAuthor INNER JOIN (tblBook INNER JOIN tblCategory ON tblBook.CatID=tblCategory.CatID) ON tblBook.AuthorID=tblAuthor.AuthorID where %1$s ORDER BY %2$s %3$s LIMIT %4$s ';
$query = sprintf($format, $where, $sortBy, $direction, $limit);
$escapedQuery = stripslashes($db->realEscape($query));
$db->runQuery($escapedQuery);
if($db->hasErrors()){
print_r($db->getErrors());
echo('<br /><br />Exiting the script.');
die();
}
$results = $db->fillResultset();
close($db);
return $results;
} //结束getbooks ?&GT;
然后调用库来处理剩下的部分。
<?php
// include header
include ("header.php");
include_once('bookFunctions.php');
$books=getBooks();
$myName = "My Books";
?>
<div id="content">
<?php if (count($books)){
?>
<table class="books">
<tr>
<th>Book Title</th>
<th>Author's Last Name</th>
<th>Author's First Name</th>
<th>Genre</th>
</tr>
<?php
foreach($books as $book)
{
echo "<tr>";//start the row
//echo out each cell
echo "<td>" . $book['Title'] . "</td>";
echo "<td>" . $book['LastName'] . "</td>";
echo "<td>" . $book['FirstName'] . "</td>";
echo "<td>" . $book['Category'] . "</td>";
echo "</tr>";//end the row
}
?>
我尝试了各种分页脚本和tuts,但我无法弄清楚将其插入到查询中的位置。我正在努力解决的最新问题是:http://stefangabos.ro/php-libraries/zebra-pagination/ 我知道必须有一些方法来做到这一点。任何建议都表示赞赏。
答案 0 :(得分:1)
如果每页第1页和第10页,您的限制条款为LIMIT 0, 10
。这是偏移0和长度10。
+------+--------+
| Page | Offset |
+------+--------+
| 1 | 0 |
| 2 | 10 |
| 3 | 20 |
+------+--------+
此处的模式为offset =(page-1)* items_per_page。
<?php
$num_per_page = 10;
$page = intval($REQUEST['page']);
$offset = ($page - 1) * $num_per_page;
$sql_limit = "LIMIT $offset, $num_per_page";
一种方法是修改函数原型以包含页面和num_per页面的参数 -
function getBooks($sortBy = 'tblAuthor.LastName', $direction='ASC', $where = 1, $page = 1, $num_per_page = 10) {
$offset = ($page - 1) * $num_per_page;
$db = connect();
$fields = array('tblBook.Title', 'tblAuthor.FirstName', 'tblAuthor.LastName', 'tblCategory.Category');
$format = 'Select '. implode(', ', $fields) .' FROM tblAuthor INNER JOIN (tblBook INNER JOIN tblCategory ON tblBook.CatID=tblCategory.CatID) ON tblBook.AuthorID=tblAuthor.AuthorID where %1$s ORDER BY %2$s %3$s LIMIT %4$d, %5$d ';
$query = sprintf($format, $where, $sortBy, $direction, $offset, $num_per_page);
然后修改你对getBooks的调用 -
$books=getBooks('tblAuthor.LastName', 'ASC', null, intval($_REQUEST['page']), 10);