沿用教程(2)的代码
第二步、在数据库中新建表并插入若干条数据
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);
第三步、给yii进行数据库连接配置,配置文件是config/db.php
<?php //配置的数据库连接可以在应用中通过 Yii::$app->db 访问 return [ 'class' => 'yii\db\Connection', 'dsn' => 'mysql:host=localhost;dbname=zhyoulun', 'username' => 'root', 'password' => '20092565', 'charset' => 'utf8', ];
第四步、在controllers/ZhyoulunController.php添加代码
public function actionCountry() { return $this->render('country'); }
第五步、在models文件夹中新建Country.php
<?php namespace app\models; use yii\db\ActiveRecord; //你不用在里面写任何代码。只需要像现在这样,Yii 就能根据类名去猜测对应的数据表名。 class Country extends ActiveRecord { }
第六步、在views/zhyoulun/文件夹中新建country.php
<?php use app\models\Country; // 获取 country 表的所有行并以 name 排序 $countries = Country::find()->orderBy('name')->all(); echo '<table border="1">'; for($i=0;$i<count($countries);$i++) { echo '<tr>'; echo '<td>'.$countries[$i]['code'].'</td>'; echo '<td>'.$countries[$i]['name'].'</td>'; echo '<td>'.$countries[$i]['population'].'</td>'; echo '</tr>'; } echo '</table>';
第七步、访问网址Http://localhost/basic/web/index.php?r=zhyoulun/country