以下是搜索结果页面分页的代码。第一页的结果显示正常但下一页显示为空白,甚至不显示导航链接。但是html
的剩余部分只是缺少结果。相同的分页代码在其他页面上工作正常,其中分页基于一些严格的值,例如WHERE category='Health'
,但在此我基于以WHERE title LIKE '%".$searchword."%'
形式提交的搜索查询进行分页。可能这是问题吗?
<form action="" method="post">
<input type="text" class="searchin" name="keyword" placeholder="Enter keyword ..."/>
<input type="submit" name="search" value="search" />
</form>
<?php
if(isset($_POST['search'])) {
$searchword = $_POST['keyword'];
$searchword = filter_var($searchword, FILTER_SANITIZE_STRING);
if( $searchword == "" ) {
$er = 'Please enter a query to search';
}
else{
$search=$db->prepare("SELECT * FROM posts WHERE title LIKE :title");
$search->execute(array(':title'=>'%".$searchword."%'));
$total=$search->rowCount();
// How many items to list per page
$limit = 10;
// How many pages will there be
$pages = ceil($total / $limit);
// What page are we currently on?
$page = min($pages, filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT, array(
'options' => array(
'default' => 1,
'min_range' => 1,
),
)));
// Calculate the offset for the query
$offset = ($page - 1) * $limit;
// Some information to display to the user
$start = $offset + 1;
$end = min(($offset + $limit), $total);
// The "back" link
$prevlink = ($page > 1) ? '<a href="?page=1" title="First page" class="pagin">«</a> <a href="?page=' . ($page - 1) . '" title="Previous page" class="pagin">‹</a>' : '<span class="disabled">«</span> <span class="disabled">‹</span>';
// The "forward" link
$nextlink = ($page < $pages) ? '<a href="?page=' . ($page + 1) . '" title="Next page" class="pagin">›</a> <a href="?page=' . $pages . '" title="Last page" class="pagin">»</a>' : '<span class="disabled">›</span> <span class="disabled">»</span>';
// Prepare the paged query
$stmt = $db->prepare("SELECT * FROM posts WHERE title LIKE :title ORDER BY posts_id DESC LIMIT
:limi
OFFSET
:offset");
$stmt->bindValue(':title', '%'.$searchword.'%', PDO::PARAM_STR);
$stmt->bindValue(':limi', $limit, PDO::PARAM_INT);
$stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
$stmt->execute();
if ($stmt->rowCount() > 0) {
// Define how we want to fetch the results
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$iterator = new IteratorIterator($stmt);
// Display the results
foreach ($iterator as $row) {
echo "<div><h2><a href='post.php?postId=" . $row['posts_id'] . "'>".$row['title']."</a></h2></div>";
}
} else {
echo "<center><h2>No matches for ".$searchword.".</h2></center>";
}
if ($search->rowCount() > 10) {
echo '<center><div class="paginate">', $prevlink, $nextlink, '</div></center>';
}
}
}
?>