php实现分页功能

sql部分:

CREATE TABLE IF NOT EXISTS `singer` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(64) NOT NULL,
`sex` char(32) NOT NULL,
`song` varchar(64) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=10 ;

--
--

INSERT INTO `singer` (`id`, `name`, `sex`, `song`) VALUES
(1, 'Lily Allen', 'F', 'Not fair'),
(2, 'Coldplay', 'M', 'Yellow'),
(3, 'Keane', 'M', 'Somewhere only we know'),
(4, 'Olivia Ong', 'F', 'Where is the love'),
(5, 'Lady Gaga', 'F', 'Just dance'),
(6, 'Lana Del Rey', 'F', 'Diet Moutain Dew'),
(7, 'Birdy', 'F', '1901'),
(8, 'Pink', 'F', 'Funhouse'),
(9, 'Kate Havnevik', 'F', 'Unlike Me');

db部分:

db.php

<?php
$config = array(
'host' => '127.0.0.1',
'username' => 'root',
'password' => '',
'database' => 'test'
);

function connect($config){
$conn = mysql_connect($config['host'],$config['username'],$config['password']);
if(!$conn){
die('could not connect'.mysql_error());
}
mysql_select_db($config['database']);
mysql_query("set names 'utf8'");
}

function get_total($tableName){
$query = "select count(*) from {$tableName}";
$result = mysql_query($query) or die('Query failed'.mysql_error());
$rows = mysql_fetch_array($result);
return ($rows?$rows[0]:0);
}

function get($tableName,$offset=0,$size=10){
$query = "select * from {$tableName} limit {$offset},{$size}";
$result = mysql_query($query) or die('Query failed'.mysql_error());
$data = array();
$len = mysql_num_rows($result);
for ($i=0; $i <$len ; $i++) {
$data[$i] = mysql_fetch_assoc($result);
}
return $data;
}

?>

页面部分:

index.php

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=utf8"/>
<title>分页原理</title>
</head>
<body>
<div align="center">
<table border="1" bgcolor="">
<tr>
<td>ID</td>
<td>NAME</td>
<td>SEX</td>
<td>SONG</td>
</tr>
<?php
include('db.php');
connect($config);
$size = 4;
$len = get_total('singer');
if($len <= 0){
$page = 1;
$total = 0;
echo '<tr colspan="4"><td>NO data</td></tr>';
}else{
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$total = ceil(($len/$size));
$data = get('singer',($page-1)*$size,$size);
for ($i=0; $i <count($data) ; $i++) {
echo '<tr>';
foreach ($data[$i] as $key => $value){
echo '<td>'.$value.'</td>';
}
echo '</tr>';
}
}

?>
</table>

</div>

<div align="center">


<?php
$pre = $page - 1;
$next = $page + 1;
if($pre > 0){
echo '<a href="index.php?page='.$pre.'">PRE</a>';
}
for ($i=1; $i <=$total; $i++) {
if($page == $i){
echo $i;
}else{
echo '<a href="index.php?page='.$i.'">'.$i.'</a>';
}
}
if($next <= $total){
echo '<a href="index.php?page='.$next.'">NEXT</a>';
}
?>
</div>

</body>
</html>

posted @ 2014-10-20 17:34  T_macgrady  阅读(65)  评论(0)    收藏  举报