PHP+MYSQL 條件篩選後分頁顯示資料

qq_2272978668發表於2017-04-03

使用PHP和MYSQL分頁顯示資料,如果再加篩選功能,則很容易與分頁功能相矛盾,這裡使用SESSION簡單解決這一問題

主要檔案 manage.php

<?php
session_start();
$username=$_SESSION['username'];
$d=date("Y-m-d");
$j=date("w");
$_SESSION['date']=isset($_SESSION['date'])?$_SESSION['date']:">='$d'";
$_SESSION['ball']=isset($_SESSION['ball'])?$_SESSION['ball']:"is not null";
$_SESSION['time']=isset($_SESSION['time'])?$_SESSION['time']:"is not null";
$date1=$_SESSION['date'];
$ball=$_SESSION['ball'];
$time=$_SESSION['time'];
header("Content-type:html/text;charset=utf-8");
?>
<link rel="stylesheet" href="../public/style.css" />
<style type="text/css">
.bga{
background-color:green;    
}
.bgb{
background-color:purple;    
}
.bgd{
background-color:#2BD4D7;    
}
.bgc{
background-color:blue;    
}
input{ border:5px thin green;color:blue;width:200px; height:30px;}
input{font-family:楷體;font-size:20px;color:#06F87C;}
font{color:purple; font-size:20px;font-weight:bold;font-family:楷體;}
//td{font-family:楷體;font-size:25px;}
button{width:100px; height:30px;}
</style>
<script src="./../public/jquery.js">
</script>
 <script>$(document).ready(function(){
    ///$('tr:even').addClass('bga');
    //$('tr:odd').addClass('bgb');
    $('tr:eq(0)').addClass('bgc');
});
$(document).ready(function(){
    $('tr:gt(0)').hover(function(){
        $(this).addClass('bgd');
    },function(){
        $(this).removeClass('bgd');
    });
});
</script>
<?php
require "./../public/init.php";
require "../public/Page.class.php";
$page = isset($_GET['page'])?(int)$_GET['page']:1;
//獲取總記錄數
$sqlx = "select count(*) as total from place where date $date1 and ball $ball and time_start $time ";
$total =$pdo->query($sqlx)->fetchColumn();
//例項化分頁類
$Page = new Page($total,8,$page); //page(總頁數,每頁顯示條數,當前頁)
//獲取limit條件
$limit = $Page->getLimit();
//獲取分頁HTML連結
$page_html = $Page->showPage();
$sql="select * from place  where date $date1 and ball $ball and time_start $time  limit $limit ";
$info=array();
$info=$pdo->query($sql)->fetchAll(PDO::FETCH_ASSOC);
?>
<?php
  if($_SESSION['status']!="管理員"){
    echo "<script>alert('非管理員,不可進入!');history.back();</script>";
}else{
?>
<div align="center">
<form name="form1" align="center" method="post" action="">
<font>球類:</font>
<select name="ball" size="1" >
<option value="is not null" selected>所有</option>
<option value="='籃球'">籃球</option>
<option value="='乒乓球'" >乒乓球</option>
<option value="='羽毛球'" >羽毛球</option>
<option value="='排球'">排球</option>
</select>
&nbsp;&nbsp;&nbsp;
<font>日期:</font><select name="date" size="1" >
<option value=">='<?php echo $d;?>'" selected>所有</option>
<?php do{ ?>
<option value="='<?php echo $d; ?>'"><?php echo $d;?>
<?php $d=date("Y-m-d",strtotime("$d+1 day"));
$j=$j+1;
?></option>
<?php }while($j<=7&&$j>1) ?>
</select>&nbsp;&nbsp;&nbsp;
<font>開始時間:</font><select name="time" size="1" >
<option value="is not null" selected>所有</option>
<option value="='08:00:00'">8:00-10:00</option>
<option value="='10:00:00'" >10:00-12:00</option>
<option value="='14:00:00'" >14:00-16:00</option>
</select>
<button type="submit" name="submit1" value="篩選" >篩選</button>
&nbsp;&nbsp;
</form>
</div>
<?php

if($_POST['submit1']=='篩選'){
    $_SESSION['ball']=$_POST['ball'];
    $_SESSION['date']=$_POST['date'];
    $_SESSION['time']=$_POST['time'];
    $date1=$_SESSION['date'];
    $ball=$_SESSION['ball'];
    $time=$_SESSION['time'];
    $page = isset($_GET['page'])?(int)$_GET['page']:1;
//獲取總記錄數
$sqlx = "select count(*) as total from place where date $date1 and ball $ball and time_start $time ";
$total =$pdo->query($sqlx)->fetchColumn();
//例項化分頁類
$Page = new Page($total,8,$page); //page(總頁數,每頁顯示條數,當前頁)
//獲取limit條件
$limit = $Page->getLimit();
//獲取分頁HTML連結
$page_html = $Page->showPage();
$sql="select * from place  where date $date1 and ball $ball and time_start $time  limit $limit ";
$info=array();
$info=$pdo->query($sql)->fetchAll(PDO::FETCH_ASSOC);
  }
$arr1=explode("'",$ball);
$ballx=$ball=="is not null"?"所有":$arr1[1];
$arr2=explode("'",$date1);
$datex=$arr2[0]==">="?"所有":$arr2[1];
$arr3=explode("'",$time);
$timex=$time=="is not null"?"所有":$arr3[1];
echo "<div align='center'>篩選條件:$ballx,$datex,$timex</div>";
?>
<div align="center">
<table valign="middle"  border="0">
<tr height="50" bgcolor="blue" >
<td width="100" align="center">球類</td>
<td width="100" align="center">場地號</td>
<td width="150" align="center">日期</td>
<td width="200" align="center">開始時間</td>
<td width="200" align="center">結束時間</td>
<td width="80" align="center">預約者</td>
<td width="100" align="center">操作</td>
</tr>
<?php
foreach($info as $v):
?>
<tr height="35">
<td align="center">&nbsp;<?php echo $v['ball']; ?></td>
<td align="center">&nbsp;<?php echo $v['No']; ?></td>
<td align="center">&nbsp;<?php echo $v['date']; ?></td>
<td align="center">&nbsp;<?php echo $v['time_start']; ?></td>
<td align="center">&nbsp;<?php echo $v['time_end']; ?></td>
<td align="center">&nbsp;<?php echo $v['UserNo']; ?></td>
<td width="100" align="center"><a href="cancel.php?id=<?php echo $v['placeNo']; ?>" title="點選此處,取消該場地的預約">取消預約</a></td>
</tr>
<?php
endforeach;
?>
</table>
</div>
<div class="pagelist"><?php echo $page_html; ?></div>
<div align="center">
<button title="預約者全部清空,所有日期都增加7" ><a href="cancelAll.php">全部置空</a></button>
</div>
<?php } ?>

使用條件查詢時,條件變數存貯在SESSION中,這樣即使使用“下一頁”來重新整理頁面,條件已經固定,因此能獲得想要的資料。由於條件表示式有所差別,理由ball="籃球" 與ball is not null  ,因此等號要放在條件值裡面,條件對應的值(例如變數名為$a1,從SESSION中獲取的值)是 “=‘籃球’”或“is not null”,內帶有變數的,外面雙引號,變數用單引號,例如:“>='$d' ”,這樣變數的值才能解析出來。所以查詢語句就變成了:sql="select * from place where ball $a1"。


載入執行的其他重要檔案包括init.php——用於連線資料庫:

<?php
header('Content-Type:text/html;charset=utf-8');
$dsn='mysql:host=localhost;dbname=ydc;charset=utf8';
$options=array(PDO::MYSQL_ATTR_INIT_COMMAND=>"SET NAMES 'UTF8' ");
//$options這句話防止輸出時,出現中文亂碼
try{
    $pdo=new PDO($dsn,'root','',$options);
}catch(PDOException $e){
    exit('PDO連線資料庫失敗:'.$e->getMessage());
}
//echo 'PDO 連線資料庫成功';

?>

控制分頁的類,所在的檔案為Page.class.php:

<?php
class Page{
    private $total;          //總記錄數
    private $pagesize;          //每頁顯示的條數
    private $current;          //當前頁
    private $maxpage;          //總頁數
    /**
     * 分頁類構造方法
     * @param $total int 總記錄數
     * @param $pagesize int 每頁顯示的條數
     * @param $current int  當前頁
     */
    public function __construct($total,$pagesize,$current){
        $this->total = $total;
        $this->pagesize = $pagesize;
        $this->current = max($current,1);
        $this->maxpage = ceil( $this->total / $this->pagesize );
    }
    //獲取SQL中的limit條件
    public function getLimit(){
        //計算limit條件
        $lim = ($this->current -1) * $this->pagesize;
        return $lim.','.$this->pagesize;
    }
    //獲得URL引數,用於在生成分頁連結時儲存原有的GET引數
    private function getUrlParams(){
        $params = $_GET;  //接收GET引數
        unset($params['page']);  //刪除引數中的page
        return http_build_query($params); //重新構造GET字串
    }
    //生成分頁連結
    public function showPage(){
        //如果少於1頁則不顯示分頁導航
        if($this->maxpage <= 1) return '';
        //獲取原來的GET引數
        $url = $this->getUrlParams();
        //拼接URL引數
        $url = $url ? '?'.$url.'&page=' : '?page=';
        //拼接“首頁”
        $first = '<a href="'.$url.'1">[首頁]</a>';
        //拼接“上一頁”
        $prev = ($this->current == 1) ? '[上一頁]' : '<a href="'.$url.($this->current-1).'">[上一頁]</a>';
        //拼接“下一頁”
        $next = ($this->current == $this->maxpage) ? '[下一頁]' : '<a href="'.$url.($this->current+1).'">[下一頁]</a>';
        //拼接“尾頁”
        $last = '<a href="'.$url.$this->maxpage.'">[尾頁]</a>';
        //組合最終樣式
        return "當前為 {$this->current}/{$this->maxpage} {$first} {$prev} {$next} {$last}";
    }
}

另外還有Jquery檔案(這裡不再多提)和用於修飾的style.css:

body{margin:0;font-family:'Microsoft YaHei';background:url('../images/bg.png');}
.box{width:1001px;margin:0 auto;}
.top{height:179px;background:url('../images/top.jpg');position:relative;}
.title{padding-left:60px;color:#000;font-size:40px;letter-spacing:5px;line-height:160px;}
.nav{position:absolute;right:0;bottom:6px;}
.nav a{color:#000;padding:6px 12px;background:#9cb945;text-decoration:none;}
.nav a:hover{color:#fff;}
.main{padding-bottom:10px;background:#fff;color:#333;}

.news-title{font-size:20px;text-align:center;padding:15px 0;width:70%;margin:0 auto;border-bottom:1px solid #999;font-weight:bold;}
.news-time{text-align:center;margin-top:10px;}
.news-content{width:70%;margin:20px auto;}

.news-edit{width:80%;margin:0 auto;padding-top:20px;}
.news-edit th{width:80px;font-weight:normal;vertical-align:top;padding-bottom:10px;}
.news-edit td{padding-bottom:10px;}
.news-edit input[type=text]{width:60%;border:1px solid #A2BBEA;padding:4px;border-radius:5px;font-family:'simsun';}
.news-edit input[type=text]:hover{background:#eeeeff;}
.news-edit textarea{width:80%;height:150px;border:1px solid #A2BBEA;padding:4px;border-radius:5px;font-family:'simsun';}
.news-edit textarea:hover{background:#eeeeff;}
.news-edit input[type=submit]{padding:5px 12px;cursor:pointer;}

.news-list{width:1000px;border-collapse:collapse;margin-bottom:10px;}
.news-list th{background:#0088cc;color:#fff;padding-top:5px;padding-bottom:5px;border:2px solid #fff;}
.news-list td{border-bottom:2px dashed #ccc;padding:8px;}
.news-list-title{text-indent:20px;}
.news-list a{color:#116FCE;text-decoration:none;}
.news-list a:hover{text-decoration:underline;}
.center{text-align:center;}

.pagelist{text-align:center;padding-bottom:10px;}
.pagelist a{color:#116FCE;text-decoration:none;}
.pagelist a:hover{text-decoration:underline;}

.action{margin-bottom:15px;}


相關文章