我很新,所以对我很轻松。我已经看过许多与此主题相关的教程和问题。我试图找出我做错了什么,因为我似乎无法使用我准备好的陈述进行分页。我的数据库目前有10行应该返回。我将尝试添加选项以便稍后插入更多行,以便更改数字。 这是数据库查询和代码。
//determine how many results are available in database
$sqlPosts = "SELECT
count(post_owner)
FROM post_table";
$stmt = $db -> prepare($sqlPosts);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($totalPosts);
$stmt->fetch();
//determine which page user is currently on
if (!isset($_GET['page']))
$current_Page = 1;
else
$current_Page = $_GET['page'];
// define how many results you want per page
$page = 1;
$rowsPerPage = 5;
//total number of available pages
$total_Pages = ceil($totalPosts/$rowsPerPage);
// determine the sql LIMIT starting number for the results on the displaying page
$start_from = ($page - 1) * $rowsPerPage;
// retrieve selected results from database and display them on page
$sql = "SELECT
body_of_post,
date_time,
post_owner,
title,
id
FROM
post_table
ORDER BY
date_time
DESC LIMIT
?,?";
$stmt = $db->prepare($sql);
$stmt->bind_param('dd', $start_from, $rowsPerPage);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($body_of_post, $date_time, $post_owner, $title, $id);
while ($stmt->fetch()) {
echo '<table border="1">
<tr>
<td bgcolor="#CCCCCC">Title</td>
<td bgcolor="#CCCCCC">Post</td>
<td bgcolor="#CCCCCC">Created by</td>
<td bgcolor="#CCCCCC">Date</td>
</tr>
<br>';
echo
'<tr><th><h2>"' . $title .'"</th>
<th>'. $body_of_post. '</th>
<th>'. $post_owner. '</th>
<th>'. $date_time. '</tr></th></h2>';
}
我认为我的问题是在while循环中,但我不确定如何编码它。分页部分应该没问题。当我单击Next链接时,我看到index.php?page =将会更新,但数据库行保持不变。我想page = 1显示数据库中的前5行而不是page = 2应显示接下来的5行,依此类推。
这是分页部分。
if($current_Page > 1){
$prev_page = $current_Page - 1;
$previous = "<a href=\"index.php?page=$prev_page\">Previous</a>";
}
if ($total_Pages > 1){
for($page = 1; $page <= $total_Pages; $page++){
if ($page == $current_Page){
$page_count = "";
}
else
echo "<a href=\"index.php?page=$page\">Next$rowsPerPage</a>";
}
echo $page_count;
}
答案 0 :(得分:1)
问题出在以下几行:
$start_from = ($page - 1) * $rowsPerPage;
您将$page
变量设置为修复1
,因此只显示第一组记录。将此行更改为
$start_from = ($current_Page - 1) * $rowsPerPage;
使用网址中提供的page
参数。