PHP的新手,无法真正弄清楚如何使用我当前的代码进行分页:
<?php
if($result = $db ->query("SELECT * FROM twentyfour ORDER BY date DESC")) {
if($result->num_rows > 0) {
echo "<table><tr><th>Category</th><th>Date</th><th>Name</th><th>Location</th></tr>";
while($row = $result->fetch_object()) {
echo '<tr><td>', $row->category, '</td><td>', $row->date = date('jS F Y',strtotime($row->date)), '<td>', $row->name, '<td>', $row->location, '</td></td></td></tr>';
}
echo "</table>";
$result->free();
}
}
?>
我尝试了多个示例尝试将其用于我的代码,但我对此并不擅长。
我试过了:http://www.webassist.com/tutorials/Numbered-Pagination-Using-MySQLi 但是用:替换顶部:
$News = $db ->query("SELECT * FROM twentyfour");
$maxRows_News =2;
$NewsTotal = $db->query("SELECT count(1) a FROM twentyfour");
$News_Total = (int)$NewsTotal->Results[0]['a'];
$Req_pages = ceil($NewsTotal/$maxRows_News);
$totalRows_News = $News_Total;
我通过观看视频得到了这个:
<?php
$per_page = 2;
if($result = $db->query("SELECT * FROM twentyfour ORDER BY id"))
{
if ($result->num_rows != 0)
{
$total_results = $result->num_rows;
$total_pages = ceil($total_results / $per_page);
if (isset($_GET['page']) && is_numeric($_GET['page']))
{
$show_page = $GET['page'];
if ($show_page > 0 && $show_page <= $total_pages)
{
$start = ($show_page -1) * $per_page;
$end = $start + $per_page;
}
else
{
$start = 0;
$end = $per_page;
}
}
else
{
$start = 0;
$end = $per_page;
}
// display pagination
echo "<p><a href='view.php'>View All</a> | <b>View Page: </b>";
for ($i = 1; $i <= $total_pages; $i++)
{
if (isset($_GET['page']) && $_GET['page'] == $i)
{
echo $i . " ";
}
else {
echo "<a href='update.php?page=$i'>" . $i . "</a> ";
}
}
echo "</p>";
// display records
for ($i = $start; $i < $end; $i++)
{
if ($i == $total_results) { break; }
}
$row = $result->fetch_object();
echo '<tr><td>', $row->category, '</td><td>', $row->date = date('jS F Y',strtotime($row->date)), '<td>', $row->name, '<td>', $row->location, '</td></td></td></tr>';
}
else
{
echo "No results!";
}
}
else
{
echo "Error: " . $mysqli->error;
}
?>
答案 0 :(得分:0)
一段非常简单的代码,用于分页。
$total = 1000; //Or do something like SELECT COUNT(*) AS a FROM table
$itemsPerPage = 30;
$numberOfPages = ceil($total/$itemsPerPage);
echo $numberOfPages; //output: 34
//Use the GET url to check which page must be opened.. else it's always 1;
$pageToOpen = is_numeric($_GET['page']) ? $_GET['page'] : 1;
echo $pageToOpen; //output: 1 (or something else if you define ?page=XXX to your url)
//Query to fetch results from database
$sqlQuery = "SELECT * FROM table LIMIT " . (($pageToOpen-1) * $itemsPerPage) . ", " . $itemsPerPage;
echo $sqlQuery; //SELECT * FROM table LIMIT 0, 30 when page is one.. SELECT * FROM table LIMIT 420, 30 when page is 15.. etc