Yii uses database operations

Source: Internet
Author: User
Tags yii

1. Install the database

If you are installing via composer, you only need to go through the command line,

Need to configure the string, 2.0 inside the yii\common\config\main-local.php

<?PHPreturn [    ' Components ' = [        ' db ' = = [            ' Class ' = ' yii\db\connection ', ' dsn ' = ' mysql:host=localhost;dbname=yii ', ' username ' = ' Root ', ' password ' = ', ' charset ' = ' utf8 ',        ], ' mailer ' = [            ' Class ' = ' Yii\swiftmailer\mailer ', ' viewPath ' = ' @common/mail ',//send all mails to a file by default. You has to set//' Usefiletransport ' to false and configure a transport///for the mailer to send R EAL emails.' Usefiletransport ' =true,        ],    ],];

Enter the C:\ProgramData\ComposerSetup\bin directory,

The implementation of Yii migrate can complete the migration of the database, and then open the homepage can be registered and login,

Looking at the database, you will find a more user table

Then create a table in the database named country and insert the simple data. You can execute the following statement:

CREATE TABLE' country ' (' Code 'CHAR(2) not NULL PRIMARY KEY, ' name 'CHAR( the) not NULL, ' population 'INT( One) not NULL DEFAULT '0') ENGINE=InnoDBDEFAULTCHARSET=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','Kingdom',59623400);INSERT  into' Country 'VALUES('inch','India',1013662000);INSERT  into' Country 'VALUES('RU','Russia',146934000);INSERT  into' Country 'VALUES('US','states',278357000);

2. Create an Activity record

Create a class that inherits from the activity record class Country , put it in a models/Country.php file, and go to represent and read country the table's data.

<? phpnamespace app\models;  Use Yii\db\activerecord; class extends activerecord{}

This Country class inherits from [[Yii\db\activerecord]]. You don't have to write any code in there. Just like now, Yii can guess the corresponding data table name based on the class name.

Add: If the class name and the data table name do not correspond directly, you can override the [[Yii\db\activerecord::tablename () |tablename ()]] method to explicitly specify the related table name.

Using Country a class makes it easy to manipulate country table data, just like this code:

 UseApp\models\country;//get all rows of the country table and sort by name$countries= Country::find ()->orderby (' name ')All ();//gets the row with the primary key "US"$country= Country::findone (' US ');//output "states"Echo $country-name;//Modify the name to "U.S.A." and save the changes in the database$country->name = ' U.S.A. ';$country->save ();

Supplement: Activity logging is an object-oriented, powerful way to access and manipulate database data. You can find more information in the Activity History section. In addition, you can manipulate database data using a more primitive method called data Access objects.

3. Create an action

In order to show the country data to the end user, you need to create an action. Creating a new controller in the site controller compared to the previous section is more reasonable for all state-related data. The new controller is named Countrycontroller and creates an index operation in it, as follows:

<?phpnamespace app\controllers; UseYii\web\controller; Useyii\data\pagination; UseApp\models\country;classCountrycontrollerextendscontroller{ Public functionActionindex () {$query= Country::find (); $pagination=Newpagination ([' Defaultpagesize ' = 5, ' TotalCount '$query-Count(),        ]); $countries=$query->orderby (' name ')            ->offset ($pagination-offset)->limit ($pagination-limit)-All (); return $this->render (' Index ', [            ' Countries ' =$countries, ' pagination ' =$pagination,        ]); }}

Save the above code in the controllers/countrycontroller.php file.

The index action invokes the active record Country::find () method to generate the query statement and retrieve all the data from the country table. To limit the number of countries returned by each request, the query is paginated with the help of [[Yii\data\pagination]] objects. The mission of the pagination object is mainly two points:

Set the offset and limit clauses for the SQL query statement to ensure that each request only returns one page of data (5 rows per page in this case).
Displays a pager in the view that consists of a list of page numbers, which is explained in a later paragraph.

At the end of the code, the index action renders a view named index and passes the national data and paging information in.

4. Create a View

In the views directory, create a subdirectory named First country . This directory stores all country views rendered by the controller. In the views/country directory, create a index.php view file named, which reads as follows:

 <? php  use   yii\helpers\html;  use   Yii\widgets\linkpager; ? >foreach  ( $countries  as   $country ):?> <li> <?= Html::encode ("{ $country ->name} ({ $country ->code})?: <?=  $country ->population?> & lt;/li><?php endforeach ;? ></ul><?= linkpager::widget ([' Pagination ' = 

This view contains two parts for displaying national data. The first part iterates through the country data and renders it in an unordered HTML list. The second section uses [[Yii\widgets\linkpager]] to render paging information from the operation. Widget Linkpager displays a list of paging buttons. Clicking on any of the buttons will jump to the corresponding page.

Yii uses database operations

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.