欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Yii2.0框架实现带分页的多条件搜索功能示例

程序员文章站 2022-06-29 22:38:55
本文实例讲述了yii2.0框架实现带分页的多条件搜索功能。分享给大家供大家参考,具体如下: 方法一 在控制器中 public function actions...

本文实例讲述了yii2.0框架实现带分页的多条件搜索功能。分享给大家供大家参考,具体如下:

方法一

在控制器中

public function actionshow(){
  $where['title']=yii::$app->request->get('title');
  $where['content']=yii::$app->request->get('content');
  $query=new query();
  $query->from('votes');
  // votes 是表名
  if(!empty($where['title'])||!empty($where['content'])){
    $query->andfilterwhere(
      ['like','title',$where['title']]
    )->orfilterwhere(
      ['like','content',$where['content']]
    );
  }
  $users=$query->from('votes')->all();
  $pages = new pagination(['totalcount' =>$query->count(),'pagesize'=>'2']);
  $users = $query->offset($pages->offset)->limit($pages->limit)->all();
  return $this->render('show',['data'=>$users,'where'=>$where,'pages'=>$pages]);
}

在v层

<?php
use yii\helpers\html;
use yii\widgets\activeform;
use yii\helpers\url;
use yii\widgets\linkpager;
?>

<?php
$form=activeform::begin([
  'action'=>url::toroute(['show']),
  'method'=>'get',
]);
echo '姓名'," ",html::input('text','title');
echo '简介'," ",html::input('text','content');
echo html::submitbutton('提交');
activeform::end();
echo "<br/>";
echo "<br/>";
?>

显示在v层的分页

<?php
echo linkpager::widget([
  'pagination'=>$pages,
  'nextpagelabel'=>'下一页',
  'firstpagelabel'=>'首页'
])
?>

方法二(不带分页  是另外一种方法)

public function actionshow(){
  $titles=yii::$app->request->post('title');
  $content=yii::$app->request->post('content');
  $where=1;
  if($titles!=""){
    $where.=" and title like '%$titles%'";
  }
  if($content!=""){
    $where.=" and content like '%$content%'";
  }
  $sql="select * from votes where $where";
  $users=yii::$app->db->createcommand($sql)->query();
  return $this->render('show',['data'=>$users]);
}

更多关于yii相关内容感兴趣的读者可查看本站专题:《yii框架入门及常用技巧总结》、《php优秀开发框架总结》、《smarty模板入门基础教程》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总

希望本文所述对大家基于yii框架的php程序设计有所帮助。