PHP面向过程简单分页例子

2017-10-16 PHP
今天用PHP做了一个简单的分页功能,比较适合新手理解分页原理,使用面向过程的方式,下面是代码,希望对大家有所帮助。
<?php
header("Content-type:text/html;charset=utf-8");
$conn = mysql_connect('localhost','root','notetirbe.com');//连接数据库
mysql_select_db('articles');//选择数据库
function table($tableName){
	echo "<table border='1'>";
		$sqls = "select * from {$tableName}";//查询所有数据
		$result = mysql_query($sqls);
		$total = mysql_num_rows($result); //总条数
		$cols = mysql_num_fields($result); //总列数

		$num = 5;//每页显示条数
		$pagenum =ceil( $total/$num); //总页数
		$url = "demo4.php"; //请求的URL
		$cpage = isset($_GET['page']) ? $_GET['page'] : 1;
		$offset = ($cpage-1)*$num;
		$start = $offset+1;
		$end = $cpage*$num;
		$prev = ($cpage ==1) ? 0 : $cpage-1;
		$next = ($page == $pagenum) ? 0 : $cpage+1;
		
		$sqls = "select * from {$tableName} limit {$offset},{$num}";//分页数据,查询结果覆盖原来的数据库
		$result = mysql_query($sqls);
		
		echo $sqls;//测试用的,不需要可以删掉
		//输出表头
		echo "<tr>";
		for($a=0;$a<$cols;$a++){
				echo "<td>";
				echo mysql_field_name($result,$a);
				echo "</td>";
			}
		echo "</tr>";
		//循环数据
		while($row = mysql_fetch_assoc($result) ){
			echo "<tr>";
			foreach($row as $col ){
					echo "<td>";
					echo $col;
					echo "</td>";
				}
			echo "</tr>";
		}
		//分页显示
		echo "<tr><td colspan='{$cols}' align='right'>";
		echo "共<b>{$total}</b>条记录&nbsp;&nbsp;本页显示<b>{$start}-{$end}条</b>&nbsp;&nbsp;当前{$cpage}/{$pagenum}页&nbsp;&nbsp;";
		if($cpage == 1){
				echo '首页';
			}else{
				echo "<a href='{$url}'>首页</a>&nbsp;&nbsp;";
				}
		if($prev){
				echo "<a href='{$url}?page={$prev}'>上一页</a>&nbsp;&nbsp;";
			}else{
				echo '上一页';
				}
		if($next){
				echo "<a href='{$url}?page={$next}'>下一页</a>&nbsp;&nbsp;";
			}else{
				echo '下一页';
				}
		if($cpage == $pagenum){
				echo '尾页';
			}else{
				echo "<a href='{$pagenum}'>尾页</a>";
				}
		echo "</tr></td>";
	echo "</table>";
	}

table('hd_article');
?>

本例子数据库下载地址 :http://www.notetribe.com/uploads/files/articles.sql