namespace frontend\controllers;
use Yii;
use yii\web\Controller;
use yii\data\Pagination;
use frontend\models\User;
class Day3Controller extends Controller{
function actionIndex()
{
$search=Yii::$app->request->get('search');
$query = User::find()->OrderBy(['id'=>SORT_ASC]); //user为model名也是表名 id排序
if($search){
$query->where(['like','name',$search]);
}
//$countQuery = clone $query;
$pages = new Pagination(['totalCount' => $query->count(),'pageSize'=>'2']);
$models = $query->offset($pages->offset)->asArray() //以数组形式 不写为对象
->limit($pages->limit)
->all();
//print_r($models);die;
foreach($models as $k=>$v){
$models[$k]=str_replace($search,"<font color='red'>".$search."</font>",$v);
}
return $this->render('index', [
'models' => $models,
'pages' => $pages,
]);
}
}
?>
view
<meta charset="utf-8">
<center>
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
$form = ActiveForm::begin([
'action' => 'index.php?r=day3/index',
'method' => 'get',
])
?>
<input type="text" name="search" /><input type="submit" value="搜索" />
<?php ActiveForm::end() ?>
<table border="1">
<th>ID</th>
<th>姓名</th>
<th>密码</th>
<?php foreach($models as $model):?>
<tr>
<td><?php echo $model['id']?></td>
<td><?php echo $model['name']?></td>
<td><?php echo $model['pwd']?></td>
</tr>
<?php endforeach?>
</table>
<?php
use yii\widgets\LinkPager;
echo LinkPager::widget([
'pagination' => $pages,
]);
?>
</center>