Yii2 Lesson - 04 Connecting to a DB and Active Records

数据库新建表users

/* show create table tablename */
CREATE TABLE `users` (
 `user_id` int(11) NOT NULL AUTO_INCREMENT,
 `username` varchar(100) NOT NULL,
 `password` varchar(32) NOT NULL,
 PRIMARY KEY (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8

新建模型类 models/User.php

<?php
namespace app\models;

use yii\db\ActiveRecord;

class Users extends ActiveRecord
{

}

创建控制器和方法controllers/UsersController.php

<?php
namespace app\controllers;

use yii\web\Controller;
use app\models\Users;

class UsersController extends Controller
{
    public function actionIndex()
    {   
        $users = Users::find()->all();
        return $this->render('index',['users'=>$users]);
    }   
}

创建显示类 views/users/index.php

<?php

foreach($users as $user)
{
    echo $user->username."<br>";
}
posted @ 2017-07-20 16:10  且聽风吟  阅读(187)  评论(0编辑  收藏  举报