Yii2.0使用数据库
程序员文章站
2022-03-05 13:41:24
...
准备好数据库:
新建一个数据库yii2basic,然后在其中创建一张表:
CREATE TABLE `country` ( `code` CHAR(2) NOT NULL PRIMARY KEY, `name` CHAR(52) NOT NULL, `population` INT(11) NOT NULL DEFAULT '0' ) ENGINE=InnoDB DEFAULT CHARSET=utf8; INSERT INTO `country` VALUES ('AU','Australia',18886000); INSERT INTO `country` VALUES ('BR','Brazil',170115000); INSERT INTO `country` VALUES ('CA','Canada',1147000); INSERT INTO `country` VALUES ('CN','China',1277558000); INSERT INTO `country` VALUES ('DE','Germany',82164700); INSERT INTO `country` VALUES ('FR','France',59225700); INSERT INTO `country` VALUES ('GB','United Kingdom',59623400); INSERT INTO `country` VALUES ('IN','India',1013662000); INSERT INTO `country` VALUES ('RU','Russia',146934000); INSERT INTO `country` VALUES ('US','United States',278357000);
配置数据库连接:
在config/db.php中:
<?php return [ 'class' => 'yii\db\Connection', 'dsn' => 'mysql:host=localhost;dbname=yii2basic', 'username' => 'root', 'password' => '', 'charset' => 'utf8', ];
创建一个ActiveRecord:
models/Country.php:
<?php namespace app\models; use yii\db\ActiveRecord; class Country extends ActiveRecord { }
创建一个Action:
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, ]); } }
创建视图
view/country/index.php:
<?php use yii\helpers\Html; use yii\widgets\LinkPager; ?> <h1>Countries</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://hostname/index.php?r=country/index
上一篇: 深入浅出ES6之let和const命令
下一篇: linux awk命令详解
推荐阅读
-
在Python中使用Neo4j数据库的教程
-
Memcached - PHP 装配&使用
-
typecho的markdown代码标签是不是有问题?代码标签该如何使用!!!在线等
-
使用HTML5/CSS3五步快速制作便签贴特效代码示例分享(图文)
-
初步使用bootstrap快速创建页面_html/css_WEB-ITnose
-
技巧文章:实用的ASP连接数据库的函数
-
有那些 像 laravel 的 migration 管理 数据库的工具?
-
Delphi开发系列(9):修改客户端数据后更新到数据库
-
初步使用bootstrap快速创建页面_html/css_WEB-ITnose
-
使用php判断浏览器的类型和语言的函数代码_php技巧