Yii应用(3)

来源:互联网 发布:mysql slave 跳过错误 编辑:程序博客网 时间:2024/05/21 06:37

Yii应用(3)

本节,我们来实现一个最基本的用户读取和注册功能。

1.创建工程名为test,下载和安装Yii,请见本BLOGYii应用(1) 

2.下载安装Mysql5.5以上版本。

创建数据库:create database test;

创建数据表:create table user(

id int(11) primary key not null auto_increment,

name char(128) not null,

password char(128) not null,

phone char(128) not null)

本机的数据库地址为127.0.0.1,用户名:root,密码为空。

3.protected文件夹下创建config文件夹,在config文件夹类新建main.php文件作为配置文件。

 

 

main.php中输入以下代码:

<?php

return array(

    'components'=>array(

     'db'=>array(

'connectionString' => 'mysql:host=127.0.0.1;dbname=test',

'emulatePrepare' => true,

'username' => 'root',

'password' => '',

'charset' => 'utf8',

),

      ),

);

详细解答,请参考资料:http://www.yiiframework.com/doc/guide/database.dao

配置文件写好了,我们来引用该配置文件,如何引用呢:

我们在入口文件index.php文件中加入以下代码:

index.php文件代码:

<?php

$yii = dirname(__FILE__).'/lib/framework/yii.php';  #Yii安装路径

$config = dirname(__FILE__).'/protected/config/main.php';  #配置文件路径

require_once($yii);

require_once($config);

Yii::createWebApplication($config)->run();

4.我们如何快速的构建CRUD,我的工程目录为C:/wamp/www/test

要想快速构建CRUD操作,有个必要的前提条件:

你的工程可用访问

例如我的工程目录如下:

 

 

SiteController.php代码如下:

<?php

class SiteController extends CController

{

    public function actionIndex()

    {

        $this->render('index');

    }

}

index.php文件内容为空。

访问一下你的地址是否可用http://localhost/test/。不可用请参考本BLOGYii应用(1) 

可用的话那么我们继续下一步

DOS中输入:

cd C:/wamp/www/test

 

 

该步骤将会生成一个User.php类,我们可以在models文件夹中查看,核对下表名。

User.php部分代码:

public function tableName()

{

return 'User';    #表名,修改成'user'

}

然后再回DOS窗口,输入:

 

 

 

出现以下窗口则完成CRUD的创建。

当然我们也可以把表名修改成不存在的表名,查看下错误信息。

虽然创建了但是还有很多地方需要手动修改!很多挂件不是我们需要的,我们要去掉!

首先第一个问题就会遇到找不到User类,我们修改配置文件

代码如下:

<?php

return array(

    'components'=>array(

        'db'=>array(

            'connectionString' => 'mysql:host=127.0.0.1;dbname=test',

            'emulatePrepare' => true,

            'username' => 'root',

            'password' => '',

            'charset' => 'utf8',

        ),

      ),

    'import'=>array(

       'application.models.*',

    )

);

当然还有就是界面要修改的了,我们根据提示进行修改就可以了。最后访问http://localhost/test/index.php?r=user/index 就可以看到实际运行结果了。

参考资料:http://www.yiiframework.com/doc/guide/

原创粉丝点击