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; //一共有多少页 //根据分页链接来修改当前页的值 if (!empty($_GET['page'])) { $pageNow = $_GET['page']; } //这里是关键词的搜索 $key=isset($_GET['key'])?'':$_GET['key'];//判断前段页面传递过来的关键词是否存在 $cid=isset($_GET['cid'])?'':$_GET['cid']; $condition='1=1'; //这个条件是保证在搜索栏中没有任何输入的时候能正常显示 if(!empty($key)){ $condition.=" and content LIKE '%{$key}%'"; } if(!empty($cid)){ $condition.=" and cid={$cid}"; } //根据分页链接来修改 $pageNow的值。 $sql = "select count(*) from list WHERE {$condition}"; //根据$condition条件来进行查询 $res1 = mysqli_query($link,$sql);//将查询的结果赋值给$res1 //取出行数 if ($row = mysqli_fetch_row($res1)) { $rowCount = $row[0]; } //取得$rowCount,,进而我们就知道了$pageCount这两个数值了 //计算共有多少页 $pageCount = ceil($rowCount / $pageSize); $pageStart = ($pageNow - 1) * $pageSize; //发送带有分页的sql结果 //根据$sql语句的limit 后面的两个值(起始值,每页条数),来实现分页。以及求得这两个值。 $sql = "select * from list WHERE {$condition} order BY id limit $pageStart,$pageSize"; $res2 = mysqli_query($link,$sql) or die('无法获取结果集' . 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="请输入搜索关键字" 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.