Also available in these languages:
DeutschEnglishEspañolFrançaisBahasa Indonesia日本語polskiPortuguêsRomâniaРусскийsvenska简体中文

Creating First Yii Application

To get an initial experience with Yii, we describe in this section how to create our first Yii application. We will use the powerful yiic tool which can be used to automate code creation for certain tasks. For convenience, we assume that YiiRoot is the directory where Yii is installed, and WebRoot is the document root of our Web server.

Run yiic on the command line as follows:

% YiiRoot/framework/yiic webapp WebRoot/testdrive

Note: When running yiic on Mac OS, Linux or Unix, you may need to change the permission of the yiic file so that it is executable. Alternatively, you may run the tool as follows,

% cd WebRoot/testdrive
% php YiiRoot/framework/yiic.php webapp WebRoot/testdrive

This will create a skeleton Yii application under the directory WebRoot/testdrive. The application has a directory structure that is is needed by most Yii applications.

Without writing a single line of code, we can test drive our first Yii application by accessing the following URL in a Web browser:

http://hostname/testdrive/index.php

As we can see, the application has four pages: the homepage, the about page, the contact page and the login page. The contact page displays a contact form that users can fill in to submit their inquiries to the webmaster, and the login page allows users to be authenticated before accessing privileged contents. See the following screenshots for more details.

Home page

Home page

Contact page

Contact page

Contact page with input errors

Contact page with input errors

Contact page with success

Contact page with success

Login page

Login page

The following diagram shows the directory structure of our application. Please see Conventions for detailed explanation about this structure.

testdrive/
   index.php                 Web application entry script file
   index-test.php            entry script file for the functional tests
   assets/                   containing published resource files
   css/                      containing CSS files
   images/                   containing image files
   themes/                   containing application themes
   protected/                containing protected application files
      yiic                   yiic command line script for Unix/Linux
      yiic.bat               yiic command line script for Windows
      yiic.php               yiic command line PHP script
      commands/              containing customized 'yiic' commands
         shell/              containing customized 'yiic shell' commands
      components/            containing reusable user components
         Controller.php      the base class for all controller classes
         Identity.php        the 'Identity' class used for authentication
      config/                containing configuration files
         console.php         the console application configuration
         main.php            the Web application configuration
         test.php            the configuration for the functional tests
      controllers/           containing controller class files
         SiteController.php  the default controller class
      data/                  containing the sample database
         schema.mysql.sql    the DB schema for the sample MySQL database
         schema.sqlite.sql   the DB schema for the sample SQLite database
         testdrive.db        the sample SQLite database file
      extensions/            containing third-party extensions
      messages/              containing translated messages
      models/                containing model class files
         LoginForm.php       the form model for 'login' action
         ContactForm.php     the form model for 'contact' action
      runtime/               containing temporarily generated files
      tests/                 containing test scripts
      views/                 containing controller view and layout files
         layouts/            containing layout view files
            main.php         the default layout for all views
         site/               containing view files for the 'site' controller
            pages/           containing "static" pages
               about.php    the view for the "about" page
            contact.php      the view for 'contact' action
            error.php        the view for 'error' action (displaying external errors)
            index.php        the view for 'index' action
            login.php        the view for 'login' action

Connecting to Database

Most Web applications are backed by databases. Our test-drive application is not an exception. To use a database, we need to tell the application how to connect to it. This is done in the application configuration file WebRoot/testdrive/protected/config/main.php, highlighted as follows,

return array(
    ......
    'components'=>array(
        ......
        'db'=>array(
            'connectionString'=>'sqlite:protected/data/testdrive.db',
        ),
    ),
    ......
);

The above code instructs Yii that the application should connect to the SQLite database WebRoot/testdrive/protected/data/testdrive.db when needed. Note that the SQLite database is already included in the skeleton application that we just generated. The database contains only a single table named tbl_user:

CREATE TABLE tbl_user (
    id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
    username VARCHAR(128) NOT NULL,
    password VARCHAR(128) NOT NULL,
    email VARCHAR(128) NOT NULL
);

If you want to try a MySQL database instead, you may use the included MySQL schema file WebRoot/testdrive/protected/data/schema.mysql.sql to create the database.

Note: To use Yii's database feature, we need to enable PHP PDO extension and the driver-specific PDO extension. For the test-drive application, we need to turn on both the php_pdo and php_pdo_sqlite extensions.

Implementing CRUD Operations

Now is the fun part. We would like to implement the CRUD (create, read, update and delete) operations for the User table we just created. This is also commonly needed in practical applications. Instead of taking trouble to write actual code, we would use the powerful yiic tool again to automatically generate the code for us. This process is also known as scaffolding.

Open a command line window, and execute the commands listed as follows,

% cd WebRoot/testdrive
% protected/yiic shell
Yii Interactive Tool v1.1
Please type 'help' for help. Type 'exit' to quit.
>> model User tbl_user
   generate models/User.php
   generate fixtures/tbl_user.php
   generate unit/UserTest.php

The following model classes are successfully generated:
    User

If you have a 'db' database connection, you can test these models now with:
    $model=User::model()->find();
    print_r($model);

>> crud User
   generate UserController.php
   generate UserTest.php
   mkdir D:/testdrive/protected/views/user
   generate create.php
   generate update.php
   generate index.php
   generate view.php
   generate admin.php
   generate _form.php
   generate _view.php

Crud 'user' has been successfully created. You may access it via:
http://hostname/path/to/index.php?r=user

In the above, we use the yiic shell command to interact with our skeleton application. At the prompt, we execute two sub-commands: model User tbl_user and crud User. The former generates a model class named User for the tbl_user table, while the latter analyzes the User model and generates the code implementing the corresponding CRUD operations.

Note: You may encounter errors like "...could not find driver", even though the requirement checker shows you have already enabled PDO and the corresponding PDO driver. If this happens, you may try to run the yiic tool as follows,

% php -c path/to/php.ini protected/yiic.php shell

where path/to/php.ini represents the correct PHP ini file.

Let's enjoy our work by browsing the following URL:

http://hostname/testdrive/index.php?r=user

This will display a list of user entries in the tbl_user table.

Click the Create User button on the page. We will be brought to the login page if we have not logged in before. After logged in, we see an input form that allows us to add a new user entry. Complete the form and click on the Create button. If there is any input error, a nice error prompt will show up which prevents us from saving the input. Back to the user list page, we should see the newly added user appearing in the list.

Repeat the above steps to add more users. Notice that user list page will automatically paginate the user entries if there are too many to be displayed in one page.

If we login as an administrator using admin/admin, we can view the user admin page with the following URL:

http://hostname/testdrive/index.php?r=user/admin

This will show us the user entries in a nice tabular format. We can click on the table header cells to sort the corresponding columns. We can also click on the buttons on each row of data to view, update or delete the corresponding row of data.

All these nice features come without requiring us to write a single line of code!

User admin page

User admin page

Create new user page

Create new user page
$Id: quickstart.first-app.txt 1653 2010-01-02 23:05:07Z qiang.xue $
If you found any typos or errors in the tutorial, please create a Yii ticket to report it. If it is a translation error, please create a Yiidoc ticket, instead. Thank you.

Total 26 comments:

#7
Great work!
by sapauljoseph at 12:42am on December 5, 2008.

Really impressive!!! It's as though it's truly a Ruby on Rails replacement. The ease with which I can start with my new project is actually far better than RoR.

Keep the great work going!

#11
AR and db modelling
by aztech at 12:34pm on December 12, 2008.

I suggest to use for generating AR/db classes Kohana approach. They just create two classes., lets call it DBClass and UserWrappedDBClass First is a representation of DB structure with AR, second is inheriting from first. All changes and development should be made in second class in case that db can change in future. Then there is possibility to regenerate first DBClass without touching UserWrappedDBClass where can be found special methods/feautures

#12
SQL schema is wrong
by celleo at 12:28am on December 15, 2008.

Please correct "AUTOINCREMENT" to "AUTO_INCREMENT". I can't believe this simple mistake can happen on the first Guide doc to all newbies.

#13
SQL is correct for sqlite
by gollyg at 12:38pm on December 15, 2008.

@celleo I think that the sql is correct for the sqlite database that is being used in the example. It is, as you say, incorrect for mysql. But then, if you were following the example you would not have encountered the issue.

http://www.sqlite.org/autoinc.html

Whilst i agree that the intro could use a bit more work, I think it might be slightly more constructive to mention your use case in your comment rather than assert it to be wrong (which it isn't!).

I am actually thrilled that there is such a well constructed php framework out there for me to play work with - cake and symfony have never 'felt right' - Yii does!

Another note for working from the command line in osx - install your developer tools (xtools) or you wont be able to run the shell app.

Thanks very much for this exciting framework!

#22
Make it work for MYSQL
by matthieu at 12:19am on December 17, 2008.

If you want to make it work with MySQL, don't waste time complaining and just do the following:

1) the correct syntax for the table creation would be:

CREATE TABLE user ( id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT, username VARCHAR(128) NOT NULL, password VARCHAR(128) NOT NULL, email VARCHAR(128) NOT NULL );

2) For a typical dev environment, the modifications in main.php :

... 'db'=>array( 'connectionString'=>'mysql:host=localhost;dbname=YourDBName', 'username'=> 'root', 'password'=> '' ) ...

Keep the good work!

#29
Sorry
by celleo at 12:53am on December 23, 2008.

@gollyg & matthieu: thanks for your correction. I didn't have sqlite installed. Anyway, it will confuse freshers if they use other DBMS.

#30
weird things with MySQL
by Bethrezen at 12:57am on December 24, 2008.

If I make crud using matthieu's tip, I can't make yii to make validations. Maybe this is because NOT NULL and VARCHAR type in MySQL?

#33
Perfect!
by leocofre at 12:44pm on December 29, 2008.

One, two, three steps and thats all!

Just using this line: 'connectionString'=>'mysql:host=localhost;dbname=db', 'username'=>'root', 'password'=>'' in config/main.php (I get it searching in the forums)

Simple =D

#35
MySQL 4
by yagitoshiro at 1:53pm on January 1, 2009.

If your MySQL version is 4.x, don't forget to add "emulatePrepare".

'db'=>array(
    'connectionString'=>'mysql:host=yourhost;dbname=yourdbname',
    'username' => 'mysql_username',
    'password' => 'mysql_password',
    'emulatePrepare' => true, // <- here!!!
),

#84
Example Site
by priya86 at 2:33am on February 19, 2009.

Hi,

Im newbie to this site.. After Install, I cant add a new user.. No clear Docs for Add New User.. then How to access the admin side.. If any Video link means it very useful to us.. then only able to know, were we have to change the code..

We need a Example Site to go thru. or Any Video Link..

Thanks priya

#212
failed to open stream
by chaval at 4:19am on April 20, 2009.

no matter if I use php -c ... I always get
Warning: require_once(C:\www\testdrive\protected/../../../yii/framework/yiic.php ): failed to open stream: No such file or directory in C:\www\testdrive\protecte d\yiic.php on line 7 Fatal error: require_once(): Failed opening required 'C:\www\testdrive\protected /../../../yii/framework/yiic.php' (include_path='.;C:\php5\pear') in C:\www\test drive\protected\yiic.php on line 7 and even changing that $yiic path to all I can imagine it allways give me the same error.

#214
fixed
by chaval at 4:56pm on April 20, 2009.

well, I had to change normal slashes to backslashes and delete a /.. in the index.php to make it work. Seems scafolding is too tricky

#245
Unable to access the mysql database.
by ajay1kumar1 at 4:45am on April 29, 2009.

Database is blank (without any table) but it shows no error on browser.Means it is not connected with mysql? Why? Syntax i used is 'db'=>array( 'connectionString'=>'mysql:host=localhost;dbname=mywebsite', 'username' => 'root', 'password' => '', 'emulatePrepare' => true, // <- here!!! ),

Thanks and regards Ajay singh rathore Cis

#308
why is the generated php files tag unclosed
by resplendent at 5:58am on May 22, 2009.

is there a reason why the generated php files <?php tags unclosed? do they post any flaw to attack?

#336
RE: why is the generated php files tag unclosed
by alexweber at 5:37pm on May 29, 2009.

The reason is that the closing tags are not only unnecessary but it's convention to avoid them in order to avoid accidentally injecting trailing white spaces and cause headers to be prematurely sent.

The closing tag should only be used when PHP and HTML are mixed in the same file (ie: views)

#351
RE: RE: why is the generated php files tag unclosed
by resplendent at 6:59am on June 3, 2009.

thanks for alexweber for your advice.

#359
Creating Your First Application in Windows
by adrianhedley at 6:09am on June 5, 2009.

I am posting an example how to create the first application in Windows because i think is may help newbies.

Example Create first Application

php path\to\yii\framework\yiic.php webapp path\to\www\ApplicationName

Example

php e:yii\framework\yiic.php webapp e:\wamp\www\test1

Note: make sure php is in the path of your Windows Environment variables

#372
pagination
by ramakrishnankt at 6:27am on June 11, 2009.

i want code for pagination in my first webapplication program given in yii guide

#415
Problem with webapp on yii-1.0.6.r1102
by mirrorps at 6:45pm on June 25, 2009.

There is a problem with release yii-1.0.6.r1102 when creating a project with console webapp ... I've tried 2 times, but when I open the index page it dies with an error (btw for the 2 trays the errors were different). So I erased the project again and after that tried with the privies release (yii-1.0.5.r1018) and it worked.

#450
Not working in XAMPP
by shinokada at 7:13am on July 7, 2009.

Ok, I tried the above code. 'db'=>array( 'connectionString'=>'mysql:host=localhost;dbname=myDBName', 'username'=> 'root', 'password'=> 'mypass' )

Then using cmd,

cd WebRoot/testdrive protected/yiic shell Yii Interactive Tool v1.0 Please type 'help' for help. Type 'exit' to quit.

model User generate User.php

But I keep getting the following error.

exception 'CDbException' with message 'CDbconnection.connectionSting cannot be empty.' in c:\xampp\htdocs\yii\framework\db\CDbConnection.php:238 Stck trace: ... ...

What do I need to do?

#495
@shinokada
by shiroamada at 7:10pm on July 23, 2009.

please read carefully u just need to input "model User" generate User.php is the output text,

please don't enter generate User.php,

For input text there will be >> in front, I also make the same mistake b4, hope this will help u

#498
username cannot be logged in...
by youkushuno at 7:44am on July 24, 2009.

i tried using this and yes, i can add, edit, delete users but when i log out and tried logging in the username and password, it doesnt recognize the username.. i think it the validate() function doesnt work.. btw, im using mysql for the db..

#697
some beginning tutorial and forum links
by ivolucien at 9:44pm on September 30, 2009.

Here are links to "Getting Started" documentation beyond the blog demo and Creating First Yii Application (you are here). I hope the convenience of having these links in one place is useful. (And to be clear, I'm not connected to these documents or their authors.)

Never worked with a framework? The whoopass tutorial - and its forum thread - Where to Start with Yii have some useful perspective.

Kevin Korb's Yii Framework + MySQL tutorial is usefully concise.

Questions? The General Discussion forum is the place to ask.

The Tips, Snippets and Tutorials forum has helpful posts on many topics.

The Tips forum above has a thread about this topic.

I'm sure that there are other valuable sites out there that folks can point to. Please reply to that thread with corrections or links to other newbie tutorials of fairly general scope. And yes, I too am a newbie.

#810
Create ARs and Models with Schema-file from DB-Designer
by userphil at 11:03pm on November 18, 2009.

I have DB-Designer. In it I have around 30 tables. With DB-Designer I create a Schema-file. How can I create the ARs and all Models out of my Schema-file? I have to change the tables quite often. So doing this by hand is quite a mess. Thx, Phil

#1118
Its a good framework but hard to get some answers
by userphil at 2:37am on February 16, 2010.

Isen't there anybody having an answer for my question?

#1178
Re: Create ARs and Models with Schema-file from DB-Designer
by jboban at 2:47am on February 26, 2010.

Good database design does not assume often tables changes. Do you really need that?

Your Comment:

You may enter comment using Markdown syntax.

Please login with your forum account.
Note: you must have at least ONE forum post with your account.