The code that follows the tutorial (2)
The first step is to create a new database in the local MySQL database Zhyoulun
Step two, create a new table in the database and insert several data
CREATE TABLE ' country ' ( ' Code ' char (2) NOT null PRIMARY KEY, ' name ' char (*) NOT NULL, ' population ' INT (one) N OT 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 (' cas ', ' 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 ', ' Manchester Kingdom ', 59623400); insert INTO ' country ' values (' in ', ' India ', 1013662000); insert INTO ' country ' VALUES (' RU ', ' Russia ', 146934000); INSERT into ' country ' values (' US ', ' Manchester states ', 278357000);
The third step, the database connection configuration for Yii, configuration file is config/db.php
<?php//configured database connection can be used in the application via Yii:: $app->db access return [ ' class ' = ' yii\db\connection ', ' dsn ' = ' MySQL: Host=localhost;dbname=zhyoulun ', ' username ' = ' root ', ' password ' = ' 20092565 ', ' charset ' and ' = ' UTF8 ',];
Fourth step, add code in controllers/zhyouluncontroller.php
Public Function Actioncountry () {return $this->render (' Country ');}
Fifth step, create a new country.php in the Models folder
<?php namespace App\models; Use yii\db\activerecord;//you don't have to write any code inside. Just like now, Yii can guess the corresponding data table name based on the class name. Class Country extends activerecord{}
Sixth step, create a new country.php in the views/zhyoulun/folder
<?phpuse app\models\country;//get all rows of country table and sort by 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> ';
Seventh step, visit the URL http://localhost/basic/web/index.php?r=zhyoulun/country
Reference: Http://www.yiichina.com/guide/2/start-databases
Reprint Please specify source: http://blog.csdn.net/zhyoulun/article/details/40454583
Yii Framework Development Tutorial (3) Getting started with MySQL database