Blogger Information
Blog 16
fans 0
comment 0
visits 10632
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
分页查询-2018年9月12日
兔子的博客
Original
734 people have browsed it

1.分页查询的原理与偏移量的计算方法

通过sql语句查询

SELECT*FROM 表名 LIMIT 偏移量,每页显示数据

通过修改偏移量来改变显示数据

实例

<?php
	$pdo=new PDO('mysql:host=127.0.0.1;dbname=php','root','root');
	$page=isset($_GET['p'])?$_GET['p']:1;
	$offset=($page-1)*5;
	$sql="SELECT*FROM staff LIMIT $offset,5";
	$stmt=$pdo->prepare($sql);
	$stmt->execute();
	$rows=$stmt->fetchAll(PDO::FETCH_ASSOC);

	//获取总记录数
	$stmt=$pdo->prepare("SELECT COUNT(*) FROM staff");
	$stmt->execute();
	$total=$stmt->fetchColumn(0);
	//计算总页数
	$pages=ceil($total/5);
?>
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>手工查询</title>
	<style type="text/css">
table{width: 800px;margin: 0 auto;text-align: center;}
th{background: #ccc;}
td{background: #999}
	</style>
</head>
<body>
	<table>
		<caption>员工信息表</caption>
			<tr>
				<th>ID</th>
				<th>姓名</th>
				<th>年龄</th>
				<th>性别</th>
				<th>工资</th>
			</tr>
			<?php foreach($rows as $row):?>
				<tr>
					<td><?php echo $row['staff_id']?></td>
					<td><?php echo $row['name']?></td>
					<td><?php echo $row['age']?></td>
					<td><?php echo $row['sex']?'女':'男'?></td>
					<td><?php echo $row['salary']?></td>
				</tr>	
			<?php endforeach;?>
	</table>
<h3>
<a href="http://127.0.0.1/php/15/demo02.php?p=1">首页</a>
	<a href="http://127.0.0.1/php/15/demo02.php?p=
	<?php
echo (($page-1)==0)?1:($page-1);
	?>">上一页</a>
<?php for($i=1;$i<$pages;$i++):?>	
<a href="http://127.0.0.1/php/15/demo02.php?p=<?php echo $i ?>"><?php echo $i;?></a>
<?php endfor;?>
	<a href="http://127.0.0.1/php/15/demo02.php?p=
	<?php
echo (($page+1)>$pages)?$pages:$page+1;
	?>">下一页</a>
		<a href="http://127.0.0.1/php/15/demo02.php?p=
	<?php
echo $pages;
	?>">尾页</a>
</h3>
<form action="" method="get">
第
<select name="p" id="">
		<?php for($i=1;$i<$pages;$i++):?>
<option value="<?php echo $i ?>"
<?php
if($page==$i){echo 'selected';}
?>
>
<?php echo $i ?>
</option>
<?php endfor;?></select>
页
<button>跳转</button>
</form>
</body>
</html>

运行实例 »

点击 "运行实例" 按钮查看在线实例


Correction status:Uncorrected

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!