Home >PHP Framework >YII >How to connect the yii framework to the database
yii framework configuration database connection
Before you begin, Please make sure you have installed the PHP PDO extension and your The PDO driver of the database used (for example, MySQL's pdo_mysql). For using relational database, This is the basic requirement. (Recommended learning: yii framework)
After the driver and extension are installed and available, open config/db.php and modify the configuration parameters inside to correspond to your database configuration. The file contains these contents by default:
<?php return [ 'class' => 'yii\db\Connection', 'dsn' => 'mysql:host=localhost;dbname=yii2basic', 'username' => 'root', 'password' => '', 'charset' => 'utf8', ];
config/db.php is a typical file-based configuration tool. This file configures the creation and initialization parameters of the database connection yii\db\Connection, and the applied SQL query is based on this database.
The database connection configured above can be accessed in the application through the Yii::$app->db expression.
信息: config/db.php 将被包含在应用配置文件 config/web.php 中, 后者指定了整个应用如何初始化。
Create active record
Create a class Country that inherits from the active record class, and put it in the models/Country.php file to represent and read country table data.
<?php namespace app\models; use yii\db\ActiveRecord; class Country extends ActiveRecord { }
This Country class inherits from yii\db\ActiveRecord. You don't need to write any code in it. Just like now, Yii can guess the corresponding data table name based on the class name.
信息: 如果类名和数据表名不能直接对应, 可以覆写 tableName() 方法去显式指定相关表名。
You can easily manipulate country table data using the Country class, like this code:
use app\models\Country; // 获取 country 表的所有行并以 name 排序 $countries = Country::find()->orderBy('name')->all(); // 获取主键为 “US” 的行 $country = Country::findOne('US'); // 输出 “United States” echo $country->name; // 修改 name 为 “U.S.A.” 并在数据库中保存更改 $country->name = 'U.S.A.'; $country->save();
Information: Active Record is an object-oriented, powerful way to access and manipulate database data . You can learn more in the Activity Logging chapter. In addition, you can also use another more native method called data access objects to manipulate database data.
Create Action
In order to display country data to end users, you need to create an action. Compared with the creation operation in the site controller mastered in the previous section, it is more reasonable to create a new controller for all country-related data here. Name the new controller CountryController and create an index action in it as follows:
<?php namespace app\controllers; use yii\web\Controller; use yii\data\Pagination; use app\models\Country; class CountryController extends Controller { public function actionIndex() { $query = Country::find(); $pagination = new Pagination([ '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 operation calls the active record Country::find() method to generate a query statement and retrieve all data from the country table. To limit the number of countries returned per request, the query is paginated with the help of yii\data\Pagination objects. The Pagination object has two main missions:
Set offset and limit clauses for SQL query statements to ensure that each request only returns one page of data (in this example, each page is 5 rows).
Displays a paginator consisting of a list of page numbers in the view, which will be explained in the following paragraphs.
At the end of the code, the index operation renders a view named index and passes the country data and paging information into it.
Create a view
First create a subdirectory named country in the views directory. This directory stores all views rendered by the country controller. Create a view file named index.php in the views/country directory with the following content:
<?php use yii\helpers\Html; use yii\widgets\LinkPager; ?> <h1>Countries</h1> <ul> <?php foreach ($countries as $country): ?> <li> <?= Html::encode("{$country->name} ({$country->code})") ?>: <?= $country->population ?> </li> <?php endforeach; ?> </ul> <?= LinkPager::widget(['pagination' => $pagination]) ?>
This view contains two parts to display country data. The first part loops through the country data and renders it as an unordered HTML list. The second part uses yii\widgets\LinkPager to render the paging information passed from the operation. The widget LinkPager displays a list of paging buttons. Clicking any button will jump to the corresponding page.
Trial run
Visit the following URL with your browser to see if it works:
http://hostname/index.php?r=country/index
The above is the detailed content of How to connect the yii framework to the database. For more information, please follow other related articles on the PHP Chinese website!