配合php 实现文章的 分页查询 条件筛选 和批量选中删除

2 篇文章 0 订阅

因为我这个案例几乎每行代码都打了注释  所以就直接奉上源代码了

 <?php 
   require_once dirname(__FILE__) .'/../functions.php';
   //检查是否登录
   bx_get_current_user();

  //===========按条件删除单行数据 以及批量删除 
   if (isset($_GET['delid'])) {
      bx_renewalmessage("delete from  posts where id in ({$_GET['delid']})");
   }
   $where = "1 = 1";
   //分页条件查询条件
   $pagewher = "";
    //如果进行了分类的条件筛选
  if(isset($_GET['category']) && $_GET['category']!=0 ){
    $where  = $where." and categories.id= {$_GET['category']}";
    $pagewher  =  $pagewher."&category={$_GET['category']}";
  }
    //如果进行了状态的条件筛选
  if (isset($_GET['status']) && $_GET['status']!='allstate') {
     $where  = $where." and posts.`status`='"."{$_GET['status']}"."'";
      $pagewher  =  $pagewher."&status={$_GET['status']}";
  }
//========= 分页参数处理
  $page = empty($_GET['page']) ? 1 : (int)$_GET['page'];  
  if ($page < 1 ) {
    $page = 1;
  }
  //每页多少条
  $size = 5;
//求出总页数
//查询一共有多少数据
$total_count = (int)bx_fetch_once("
   SELECT
    count(1)  as count
   from posts
   INNER JOIN categories on posts.category_id = categories .id 
   INNER JOIN users ON posts.user_id = users.id WHERE {$where}")['count'];
//总页数
$total_pages = (int)ceil($total_count / $size);
if ($page > $total_pages ) {
  $page = $total_pages;
  }
   //计算出越过多少条
  $offset = ($page -1) * $size;
//==============获取所有的posts 和 category 和 users 信息
   $current_posts = bx_fetch_all("
   SELECT
   posts.id,
   posts.title,
   posts.created , 
   categories.name as categoryName,
   users.nickname as userName,
   posts.`status` 
   from posts
   INNER JOIN categories on posts.category_id = categories .id 
   INNER JOIN users ON posts.user_id = users.id
   WHERE {$where}
   ORDER BY  posts.created DESC  
   limit {$offset} ,${size}");
 
// 查找所有的分类
  $current_categories = bx_fetch_all("select id , name from categories");
//=======分页页码处理
// $page => 101
//一共展示多少页码
$visiables = 5;
//左右一共有多少页码
$region = ($visiables-1)/2;
// $region  => 2
//开始页码
$begin = $page - $region;
// $begin => 99
//结束页码
$end = $begin + $visiables;
 //  $end => 104;

//====判断begin 和 end 不合理的情况
if($begin < 1){
  $begin = 1;
  $end = $begin + $visiables;
}
if($end > $total_pages+1){
  $end = $total_pages+1;
  $begin = $end - $visiables;
  if($begin < 1){
    $begin = 1;
  } 
}
//==========数据格式转换
   function bx_convert_status($status){
      $dist = array('drafted' => '草稿','published' => '已发布','trashed' => '回收站');
      echo isset($dist[$status]) ? $dist[$status] :  "未知状态";
   }
    function getAget($b){
      $timestamp = strtotime($b);
      return date('Y年m月d日<b\r>H:i:s',$timestamp);
   }
  ?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8">
  <title>Posts &laquo; Admin</title>
  <link rel="stylesheet" href="/static/assets/vendors/bootstrap/css/bootstrap.css">
  <link rel="stylesheet" href="/static/assets/vendors/font-awesome/css/font-awesome.css">
  <link rel="stylesheet" href="/static/assets/vendors/nprogress/nprogress.css">
  <link rel="stylesheet" href="/static/assets/css/admin.css">
  <script src="/static/assets/vendors/nprogress/nprogress.js"></script>
</head>
<body>
  <script>NProgress.start()</script>
  <div class="main">
    <?php include 'inc/navbar.php' ?>
    <div class="container-fluid">
      <div class="page-title">
        <h1>所有文章</h1>
        <a href="post-add.php" class="btn btn-primary btn-xs">写文章</a>
      </div>
      <!-- 有错误信息时展示 -->
      <!-- <div class="alert alert-danger">
        <strong>错误!</strong>发生XXX错误
      </div> -->
      <div class="page-action">
        <!-- show when multiple checked -->
        <a class="btn btn-danger btn-sm" id="deleteall" href="javascript:;" style="display: none">批量删除</a>
        <form class="form-inline" action="<?php echo $_SERVER['PHP_SELF'] ?>" method="get">
          <select name="category" id="category"  class="form-control input-sm">
           <option value="0">
                所有分类
              </option>
            <?php foreach ($current_categories as $key => $category): ?>
              <option value="<?php echo $category['id']; ?>" 
              <?php echo isset($_GET["category"])&& $_GET["category"] === $category['id'] ? " selected" : "";?>>
                <?php echo $category['name']; ?>
              </option>
            <?php endforeach ?>
          </select>
          <select name="status" id="status" class="form-control input-sm">
            <option value="allstate">所有状态</option>
            <option value="drafted" <?php echo isset($_GET["status"])&& $_GET["status"] === "drafted" ? " selected" : "";?>>草稿</option>
            <option value="published" <?php echo isset($_GET["status"])&& $_GET["status"] === "published" ? " selected" : "";?>>已发布</option>
             <option value="trashed" <?php echo isset($_GET["status"])&& $_GET["status"] === "trashed" ? " selected" : "";?>>回收站</option>
          </select>
          <button class="btn btn-default btn-sm" type="submit">筛选</button>
        </form>
        <ul class="pagination pagination-sm pull-right">
          <li class="<?php echo $page === 1 ? "disabled" : "" ; ?>" >
             <a href='?page=<?php $uppage = (int)$page-1;  echo "{$uppage}"."{$pagewher}"; ?>'>上一页</a>
          </li>
          <?php for ($i= $begin; $i < $end; $i++) : ?> 
          <li class='<?php echo $i === $page ? ' active' : ' '; ?>'><a href="?page=<?php echo $i."{$pagewher}" ?>"><?php echo $i; ?></a></li>
          <?php endfor ?>
          <li class="<?php echo $page === $total_pages ? "disabled" : "" ; ?>">
          <a href='?page=<?php $uppage = (int)$page+1;  echo "{$uppage}"."{$pagewher}";?>'>下一页</a>
          </li>
        </ul>
      </div>
      <table class="table table-striped table-bordered table-hover">
        <thead>
          <tr>
            <th class="text-center" width="40" >
            <input type="checkbox" id="allcheck"></th>
            <th>标题</th>
            <th>作者</th>
            <th>分类</th>
            <th class="text-center">发表时间</th>
            <th class="text-center">状态</th>
            <th class="text-center" width="100">操作</th>
          </tr>
        </thead>
        <tbody>
         <?php foreach ($current_posts as $key => $item): ?>
            <tr>
            <td class="text-center"><input type="checkbox" data-id = "<?php echo $item['id'];  ?>"></td>
            <td>
                <?php echo $item['title']; ?></td>
            <td>
                <?php echo $item['userName']; ?>
            </td>
            <td>
               <?php echo $item['categoryName']; ?>
            </td>
            <td class="text-center">
                <?php echo getAget($item['created']); ?>
            </td>
            <td class="text-center">
                <?php  bx_convert_status($item['status']);?>
            </td>
            <td class="text-center">
              <a class="btn btn-default btn-xs">编辑</a>
              <a class="btn btn-danger btn-xs" href="?delid=<?php echo $item['id']."{$pagewher}"; ?>">删除</a>
            </td>
          </tr>
         <?php endforeach ?>
        </tbody>
      </table>
    </div>
  </div>
  <?php include 'inc/aside.php' ?>
  <script src="/static/assets/vendors/jquery/jquery.js"></script>
  <script src="/static/assets/vendors/bootstrap/js/bootstrap.js"></script>

  <script type="text/javascript">
      $(function(){
        //存放所有被选中的id
        let delete_id = [];
        //获取所有可以被删除的checkbox
        let checkboxslist = $("tbody input[type = 'checkbox']");
       //获取全选checkbox 
        let allcheck = $("#allcheck");
        //获取批量删除按钮
        let deleteall = $("#deleteall")
        /**
         * 监听全选checkbox注册监听  如果checked 为true 
         * 遍历所有可以删除的checkbox 把他们设置为选中状态
         * 获取自定义属性 data-id 把他们保存在 delete_id 中
         *
         * 监听delete_id 中length长度  如果不为0就显示批量删除的按钮
         */
        allcheck.on('change',function(){
          if($(this).prop('checked')){
            checkboxslist.each(function(i,val){
              $(val).prop('checked',true);
              delete_id.push($(val).attr('data-id'))
            });
          }
          delete_id.length ? deleteall.fadeIn() : deleteall.fadeOut();
        });
        /**
         * 给所有可以被删除的checkbox设置change监听
         * 如果被改变的checkbox的checked属性为true  
         * 则把他的data-id属性添加到delete_id中
         * 如果被改变的checkbox的checked属性为false
         * 则 设置全选checkbox 为非选中状态
         * 删除delete_id数组中 当前checkbox中data-id中的值
         */
        checkboxslist.on('change',function(){
          let id = $(this).attr('data-id');
          if($(this).prop('checked')){
            delete_id.push(id);
          }else{
            allcheck.prop("checked",false);
            delete_id.splice(delete_id.indexOf(id),1);
          }
          delete_id.length ? deleteall.fadeIn() : deleteall.fadeOut();
        });
        deleteall.on('click',function(){
          delete_id = [];
          checkboxslist.each(function(i,v){
            if($(v).prop('checked')){
                 delete_id.push($(v).attr("data-id"));
            }
          });
          let link = "?delid="+delete_id.toString()+"<?php echo "{$pagewher}"; ?>"
          window.location.href=link; 
        });
      });
  </script>
  <script>NProgress.done()</script>
</body>
</html>

效果图:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值