您的位置:首页 > 编程语言 > PHP开发

Yii框架搜索分页

2016-10-25 19:30 627 查看
controller: 

//搜索分页

    public function actionList()
    {
        $where = Yii::$app->request->get();
//        var_dump($where);
        $query = new Query();//刚写成 $query = new\yii\db\Query();报错,所以以后报错的时候多看看上面的use...
        $query->from("user");
        if (!empty($where['name'])){
        $query->andWhere(["name"=>$where['name']]);
        }

         if (!empty($where['id1'])&&$where['id1']!==""){
             $query->andWhere([">=","id",$where['id1']]);
         }

         if (!empty($where['id2'])&&$where['id2']!==""){
             $query->andWhere(["<=","id",$where['id2']]);
         }
         //$user = $query->all();//执行上面所有的语句
        //$count = count($user);
        /*分页*/
//        $pagination = new Pagination(['totalCount' => $count,'pageSize'=>2]);
        $pagination = new Pagination(['totalCount' => $query->count()]);
        $pagination->setPageSize(2);
        $user = $query->offset($pagination->offset)->limit($pagination->limit)->all();

        return $this->render("list",['user'=>$user,'where'=>$where,'pagination'=>$pagination]);

    }
 

 

view:<?php
use yii\widgets\ActiveForm;
use yii\helpers\Url;
use yii\helpers\Html;

?>
<?php
    $form = ActiveForm::begin([
            'action'=> Url::toRoute(['show/list']),
            'method'=>'get',
        ]);
    echo "姓名:",Html::input('text','name');
    echo "ID:",Html::input('text','id1');
    echo  "-",Html::input('text','id2');

    echo Html::submitButton("搜索");
    ActiveForm::end();
?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>搜索结果展示</title>
</head>
<body>
    <table border="1">
        <tr>
            <td>ID</td>
            <td>用户名</td>

        </tr>
        <?php foreach    ($user as $key => $value) { ?>
            <tr>
                <td><?php echo $value["id"];?></td>
                <td><?php echo $value["name"];?></php></td>

            </tr>
    <?php } ?>

    </table>
</body>
</html>

<?php
use yii\widgets\LinkPager;
    echo LinkPager::widget([
        'pagination'=>$pagination,
        'nextPageLabel'=>'下一页',
        'firstPageLabel'=>'首页',
        ]
    )?>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  php Yii 搜索 分页