我只是花了一些时间来完成以下教程(我把它转换为PDO而不是mysqli): PHP + MySQL Pagination tutorial 这是它的外观:
<html>
<head>
<title>Pagination</title>
<!-- Bootstrap CDN -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<?php
if (isset($_GET['pageno'])) {
$pageno = $_GET['pageno'];
} else {
$pageno = 1;
}
$no_of_records_per_page = 10;
$offset = ($pageno-1) * $no_of_records_per_page;
$conn=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
die();
}
$total_pages_sql = "SELECT COUNT(*) FROM table";
$result = mysqli_query($conn,$total_pages_sql);
$total_rows = mysqli_fetch_array($result)[0];
$total_pages = ceil($total_rows / $no_of_records_per_page);
$sql = "SELECT * FROM table LIMIT $offset, $no_of_records_per_page";
$res_data = mysqli_query($conn,$sql);
while($row = mysqli_fetch_array($res_data)){
//here goes the data
}
mysqli_close($conn);
?>
<ul class="pagination">
<li><a href="?pageno=1">First</a></li>
<li class="<?php if($pageno <= 1){ echo 'disabled'; } ?>">
<a href="<?php if($pageno <= 1){ echo '#'; } else { echo "?pageno=".($pageno - 1); } ?>">Prev</a>
</li>
<li class="<?php if($pageno >= $total_pages){ echo 'disabled'; } ?>">
<a href="<?php if($pageno >= $total_pages){ echo '#'; } else { echo "?pageno=".($pageno + 1); } ?>">Next</a>
</li>
<li><a href="?pageno=<?php echo $total_pages; ?>">Last</a></li>
</ul>
</body>
</html>
但我遇到了一个问题:此脚本仅针对已预定义的SQL查询进行分页。但是,如果我想要一个&#34;搜索&#34;只有在用户点击&#34;搜索&#34;之后,分页脚本才会开始工作。而不是预定义的&#34;选择*&#34;?是否可以使用上述脚本或我需要更改它?
答案 0 :(得分:1)
创建HTML表单,例如
<form id="form" action="<?= $_SERVER['PHP_SELF'] ?>">
<input type="text" name="search" value="<?= !empty($_GET['search']) ?
htmlspecialchars($_GET['search']) : '' ?>">
<input type="submit" value="Search">
<input type="hidden" id="page" name="page" value="<?= !empty($_GET['page']) ?
intval($_GET['page']) : '' ?>">
<!-- add another fields here -->
</form>
...
<a href="" class="page">1</a>
<a href="" class="page">2</a>
并在脚本顶部添加:
if (!empty($_GET['search']) {
// write SQL queries for pagination and other form processing logic here
}
要将网址中的page
参数include jQuery传递到您的脚本,并将以下代码添加到页面的head
部分:
$(document).ready(function(){
$('.page').click(function(e) {
e.preventDefault();
$('#page').val($(this).html());
$('#form').submit();
});
});
此代码会阻止链接的默认操作,将页面值设置为带有#page
id的表单输入并提交。