1,创建一个名为 yii2 的数据库,
2,在数据库中创建一个名为 country 的表并插入简单的数据
3,配置数据库,打开config/db.php
- <?php
- return [
- 'class' => 'yii\db\Connection',
- 'dsn' => 'mysql:host=localhost;dbname=yii2',
- 'username' => 'root',
- 'password' => '',
- 'charset' => 'utf8',
- ];
创建活动记录(model)
创建一个继承自 活动记录类的类Country,把它放在 models/Country.php- <?php
- namespace app\models;
- use yii\db\ActiveRecord;
- class Country extends ActiveRecord
- {
- }
创建操作(controller)controllers/CountryController.php
- <?php
- namespace app\controllers;
- use yii\web\Controller;
- use yii\data\Pagination;
- use app\models\Country;
- class CountryController extends Controller
- {
- public function actionIndex()
- {
- $query = Country::find();
- $pagination = new Pagination([
- 'defaultPageSize' => 5,
- 'totalCount' => $query->count(),
- ]);
- $countries = $query->orderBy('name')
- ->offset($pagination->offset)
- ->limit($pagination->limit)
- ->all();
- return $this->render('index', [
- 'countries' => $countries,
- 'pagination' => $pagination,
- ]);
- }
- }
创建视图
在views 目录下先创建一个名为 country 的子目录,在 views/country 目录下创建一个名为 index.php 的视图文件- <?php
- use yii\helpers\Html;
- use yii\widgets\LinkPager;
- ?>
- <h1>输出如下</h1>
- <ul>
- <?php foreach ($countries as $country): ?>
- <li>
- <?= Html::encode("{$country->name} ({$country->code})") ?>:
- <?= $country->population ?>
- </li>
- <?php endforeach; ?>
- </ul>
- <?= LinkPager::widget(['pagination' => $pagination]) ?>
尝试访问
http://localhost/test2(项目名)/web/index.php?r=country/index
版权声明:本文为mengke1124原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。