List paging display and keyword search
In this section, we will talk about the paging display and keyword search functions.
To do the paging function, we must first connect to the database and obtain data. In most cases we can write paging and search functions in the same php page.
Then let’s analyze the process of the paging function:
First we need to set how many items are displayed on each page and how many pieces of data there are in total, so that we know how many pages there are in total, and This is the page we are currently on.
Let’s compare the code to explain in detail:
<?php //分頁功能 $pageSize = 5; //每頁顯示多少條記錄 $rowCount = 0; //共有多少條記錄 $pageNow = 1; //希望顯示第幾頁 $pageCount = 0; //一共有多少頁 //根據(jù)分頁鏈接來修改當(dāng)前頁的值 if (!empty($_GET['page'])) { $pageNow = $_GET['page']; } //這里是關(guān)鍵詞的搜索 $key=isset($_GET['key'])?'':$_GET['key'];//判斷前段頁面?zhèn)鬟f過來的關(guān)鍵詞是否存在 $cid=isset($_GET['cid'])?'':$_GET['cid']; $condition='1=1'; //這個(gè)條件是保證在搜索欄中沒有任何輸入的時(shí)候能正常顯示 if(!empty($key)){ $condition.=" and content LIKE '%{$key}%'"; } if(!empty($cid)){ $condition.=" and cid={$cid}"; } //根據(jù)分頁鏈接來修改 $pageNow的值。 $sql = "select count(*) from list WHERE {$condition}"; //根據(jù)$condition條件來進(jìn)行查詢 $res1 = mysqli_query($link,$sql);//將查詢的結(jié)果賦值給$res1 //取出行數(shù) if ($row = mysqli_fetch_row($res1)) { $rowCount = $row[0]; } //取得$rowCount,,進(jìn)而我們就知道了$pageCount這兩個(gè)數(shù)值了 //計(jì)算共有多少頁 $pageCount = ceil($rowCount / $pageSize); $pageStart = ($pageNow - 1) * $pageSize; //發(fā)送帶有分頁的sql結(jié)果 //根據(jù)$sql語句的limit 后面的兩個(gè)值(起始值,每頁條數(shù)),來實(shí)現(xiàn)分頁。以及求得這兩個(gè)值。 $sql = "select * from list WHERE {$condition} order BY id limit $pageStart,$pageSize"; $res2 = mysqli_query($link,$sql) or die('無法獲取結(jié)果集' . mysqli_connect_error()); $prev = ($pageNow - 1 <= 0 )?1:$pageNow-1; //上一頁 $next = ($pageNow + 1 > $pageCount)?$pageCount:$pageNow+1; //下一頁 ?>
We put paging and keyword search on one page.
In our front-end page, we also need to make some changes:
<a href="?page=<?php echo $prev;?>">上一頁</a> <?php for($i=1; $i<=$pageCount; $i++):?> <a href="?page=<?php echo $i;?> " <?php echo $i;?></a> <a href="?page=<?php echo $next;?>">下一頁</a>
The search function needs to cycle out the data we search based on keywords on the front-end page.
<li> <input type="text" placeholder="請輸入搜索關(guān)鍵字" name="key" class="input" style="width:250px; line-height:17px;display:inline-block" value="<?php echo $_GET['key'];?>"/> <input type="submit" name="sub" class="button border-main icon-search" value="搜索" /> </li>
The above is the paging and keyword search we introduced. If there is anything you don’t understand, you can leave a message and I will help you answer it in time.