Home > PHP Framework > YII > body text

How to connect the yii framework to the database

(*-*)浩
Release: 2019-11-27 13:57:43
Original
3232 people have browsed it

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 [
    &#39;class&#39; => &#39;yii\db\Connection&#39;,
    &#39;dsn&#39; => &#39;mysql:host=localhost;dbname=yii2basic&#39;,
    &#39;username&#39; => &#39;root&#39;,
    &#39;password&#39; => &#39;&#39;,
    &#39;charset&#39; => &#39;utf8&#39;,
];
Copy after login

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 中, 后者指定了整个应用如何初始化。
Copy after login

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
{
}
Copy after login

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() 方法去显式指定相关表名。
Copy after login

You can easily manipulate country table data using the Country class, like this code:

use app\models\Country;
// 获取 country 表的所有行并以 name 排序
$countries = Country::find()->orderBy(&#39;name&#39;)->all();
// 获取主键为 “US” 的行
$country = Country::findOne(&#39;US&#39;);
// 输出 “United States”
echo $country->name;
// 修改 name 为 “U.S.A.” 并在数据库中保存更改
$country->name = &#39;U.S.A.&#39;;
$country->save();
Copy after login

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([
            &#39;defaultPageSize&#39; => 5,
            &#39;totalCount&#39; => $query->count(),
        ]);

        $countries = $query->orderBy(&#39;name&#39;)
            ->offset($pagination->offset)
            ->limit($pagination->limit)
            ->all();

        return $this->render(&#39;index&#39;, [
            &#39;countries&#39; => $countries,
            &#39;pagination&#39; => $pagination,
        ]);
    }
}
Copy after login

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([&#39;pagination&#39; => $pagination]) ?>
Copy after login

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
Copy after login

How to connect the yii framework to the database

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!

Related labels:
yii
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template