1.创建数据库并插入数据
create database shop;
use shop;
CREATE TABLE ecs_goods (
goods_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
goods_name VARCHAR(32) NOT NULL,
market_price VARCHAR(32) NOT NULL,
PRIMARY KEY(goods_id));
select * from ecs_goods;
INSERT INTO ecs_goods VALUES(1,'KD876','166.60'),(2,'KD111','164.60');
INSERT INTO ecs_goods VALUES(3,'KD876','169.60'),(4,'KD111','170.60');
INSERT INTO ecs_goods VALUES(5,'KD876','177.60'),(6,'KD111','179.60');
INSERT INTO ecs_goods VALUES(7,'KD876','187.60'),(8,'KD111','199.60');
INSERT INTO ecs_goods VALUES(9,'KD876','1607.60'),(10,'KD111','1609.60');
2.编写page.class.php程序实现商品分页的功能
total = ceil($total/$size);
//每页的记录数
$this->size = $size;
//为URL添加GET参数
$this->url = $this->setUrl($url);
//获得当前页码
$this->page = $this->getNowPage();
}
/**
*获得当前页码
*/
private function getNowPage()
{
$page = !empty($_GET['page']) ? $_GET['page']:1;
if($page<1){
$this->page = 1;
}else if($page> $this->total){
$page = $this->total;
}
return $page;
}
/**
*位URL添加Get参数,去掉page参数
*/
private function setUrl($url)
{
$url .='?';
foreach ($_GET as $k => $v) {
if($k!='page'){
$url.="$k=$v&";
}
}
return $url;
}
/**
*获得分页导航
*/
public function getPageList(){
//总页数不超过1时直接返回空结果
if($this->total<=1)
{
return '';
}
//拼接分页导航的HTML
$html ='';
if($this->page>4){
$html ="url}page=1')\">1...";
}
for ($i=$this->page-3,$len=$this->page+3 ;$i<=$len && $i<=$this->total; $i++){
if($i>0){
if($i == $this->page){
$html .="url}page=$i')\" class = \"curr\">$i";
}else {
$html .="url}page=$i')\">$i";
}
}
}
if ($this->page+3<$this->total) {
$html .="...url}page={$this->total}')\">{$this->total}";
}
return $html;
}
public function getLimit(){
if ($this->total == 0) {
return '0,0';
}
return ($this->page-1)*$this->size.",{$this->size}";
}
}
?>
3.创建获取商品列表的data.php程序,实现每页显示3条记录的功能。
'SET NAMES \'UTF8\'');
//创建数据库连接
try
{
$pdo = new PDO($dsn,$user,$pwd,$options);
//echo 'PDO数据库连接成功!';
//SQL预处理语句
$stmt1 = $pdo->query("select count(*) from ecs_goods");
//var_dump($stmt1);
//实例化分页类对象
$total = $stmt1->fetchColumn();
$per = 3;
$page = new page($total,$per,'./data.php');
//执行SQL语句
$stmt = $pdo->prepare("select goods_id,goods_name,market_price from ecs_goods limit ".$page->getLimit());
//获得页码列表信息
$pageList = $page->getPageList();
//执行SQL预处理语句
$stmt->execute();
}
catch(PDOException $e)
{
echo $e->getMessage().'
';
}
//查询-结果
$data = $stmt ->fetchAll(PDO::FETCH_ASSOC);
//将分页信息追加到$data数组中
$data[] = $pageList;
//输出页面
//var_dump($data);
echo json_encode($data);
?>
4.创建一个home.html文件,使用Ajax获取服务器端的数据
商品列表
Ajax实现商品列表无刷新分页
5.运行结果