【发布时间】:2018-12-12 06:55:05
【问题描述】:
我正在努力理解使用 php 和 mysql 引入分页的最佳方法。我有下面的代码,我试图显示前 5 个按钮,例如 1-5,但我想要一个“下一个按钮”然后显示 5-10,然后显示 10-15 等等。非常感谢任何帮助。
$q=mysql_query("SELECT * FROM posts WHERE $ctq approved=1 Limit 15");
$pages = ceil(mysql_num_rows($q)/$item_per_page)+1;
//create pagination
if($pages > 0)
{
for($i = 1; $i<$pages; $i++)
{
$pagination .= '<a href="#" id="'.$i.'-page" class="inactive paginate_click">'.$i.'</a>';
}
}
$ctajax='';
if(isset($_GET['cat_id']) && !empty($_GET['cat_id'])){
$ctajax.=",'cat_id':".$_GET['cat_id'];
}
?>
<script type="text/javascript">
jQuery(document).ready(function($) {
$("#results").load("fetch_pages.php", {'page':0<?php echo $ctajax ?>}, function() {
$("#1-page").removeClass('inactive').addClass('current');
});
//initial page number to load
$(".paginate_click").click(function (e) {
$("#results").prepend('<div class="loading-indication"><img src="ajax-loader.gif" /> Loading...</div>');
var clicked_id = $(this).attr("id").split("-"); //ID of clicked element, split() to get page number.
var page_num = parseInt(clicked_id[0]); //clicked_id[0] holds the page number we need
$('.paginate_click').addClass('inactive');
$('.paginate_click').removeClass('current'); //remove any active class
//post page number and load returned data into result element
//notice (page_num-1), subtract 1 to get actual starting point
$("#results").load("fetch_pages.php", {'page':(page_num-1)}, function(){
});
$(this).addClass('current'); //add active class to currently clicked element (style purpose)
return false; //prevent going to herf link
});
});
</script>
<div id="results"></div>
<nav role="navigation" id="nav-below" class="site-navigation paging-navigation clearfix">
<div class="pagination">
<?php echo $pagination; ?>
<a href="#" id="<?php echo $iadd;?>-page" class="inactive paginate_click">Next</a>
</div>
</nav>
<?php } ?>
<!-- #nav-below -->
</section>
<!-- /#content -->
【问题讨论】:
-
请阅读SQL injection。不要使用字符串连接构建查询,而是使用prepared statements 和bound parameters。请参阅 this page 和 this post 了解一些很好的示例。
-
感谢您的回复,不幸的是我是一个初学者,所以我正在寻找一个基本的解释来展示我如何使用现有的过时代码“我知道不理想”来实现我的目标。
标签: php mysql pagination