search
HomePHP FrameworkYIIHow to connect the yii framework to the database

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;,
];

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(&#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();

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,
        ]);
    }
}

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 id="Countries">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]) ?>

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

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!

Statement
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
Beyond the Hype: Assessing Yii's Role TodayBeyond the Hype: Assessing Yii's Role TodayApr 25, 2025 am 12:27 AM

Yii remains a powerful choice for developers. 1) Yii is a high-performance PHP framework based on the MVC architecture and provides tools such as ActiveRecord, Gii and cache systems. 2) Its advantages include efficiency and flexibility, but the learning curve is steep and community support is relatively limited. 3) Suitable for projects that require high performance and flexibility, but consider the team technology stack and learning costs.

Yii in Action: Current Applications and ProjectsYii in Action: Current Applications and ProjectsApr 24, 2025 am 12:03 AM

Yii framework is suitable for enterprise-level applications, small and medium-sized projects and individual projects. 1) In enterprise-level applications, Yii's high performance and scalability make it outstanding in large-scale projects such as e-commerce platforms. 2) In small and medium-sized projects, Yii's Gii tool helps quickly build prototypes and MVPs. 3) In personal and open source projects, Yii's lightweight features make it suitable for small websites and blogs.

Using Yii: Creating Robust and Scalable Web SolutionsUsing Yii: Creating Robust and Scalable Web SolutionsApr 23, 2025 am 12:16 AM

The Yii framework is suitable for building efficient, secure and scalable web applications. 1) Yii is based on the MVC architecture and provides component design and security features. 2) It supports basic CRUD operations and advanced RESTfulAPI development. 3) Provide debugging skills such as logging and debugging toolbar. 4) It is recommended to use cache and lazy loading for performance optimization.

Yii's Purpose: Building Web Applications Quickly and EfficientlyYii's Purpose: Building Web Applications Quickly and EfficientlyApr 22, 2025 am 12:07 AM

Yii's purpose is to enable developers to quickly and efficiently build web applications. Its implementation is implemented through the following methods: 1) Component-based design and MVC architecture to improve code maintainability and reusability; 2) Gii tools automatically generate code to improve development speed; 3) Lazy loading and caching mechanism optimization performance; 4) Flexible scalability to facilitate integration of third-party libraries; 5) Provide RBAC functions to handle complex business logic.

Yii's Versatility: From Simple Sites to Complex ProjectsYii's Versatility: From Simple Sites to Complex ProjectsApr 21, 2025 am 12:08 AM

Yiiisversatileavssuitable Projectsofallsizes.1) Simple Sites, YiiOofferseassetupandrapiddevelopment.2) ForcomplexProjects, ITModularityandrbacSystemManagescalabilityandSecurity effective.

Yii and the Future of PHP FrameworksYii and the Future of PHP FrameworksApr 20, 2025 am 12:11 AM

The Yii framework will continue to play an important role in the future development of PHP frameworks. 1) Yii provides efficient MVC architecture, powerful ORM system, built-in caching mechanism and rich extension libraries. 2) Its componentized design and flexibility make it suitable for complex business logic and RESTful API development. 3) Yii is constantly updated to adapt to modern PHP features and technical trends, such as microservices and containerization.

Yii in Action: Real-World Examples and ApplicationsYii in Action: Real-World Examples and ApplicationsApr 19, 2025 am 12:03 AM

The Yii framework is suitable for developing web applications of all sizes, and its advantages lie in its high performance and rich feature set. 1) Yii adopts an MVC architecture, and its core components include ActiveRecord, Widget and Gii tools. 2) Through the request processing process, Yii efficiently handles HTTP requests. 3) Basic usage shows a simple example of creating controllers and views. 4) Advanced usage demonstrates the flexibility of database operations through ActiveRecord. 5) Debugging skills include using the debug toolbar and logging system. 6) Performance optimization It is recommended to use cache and database query optimization, follow coding specifications and dependency injection to improve code quality.

How to display error prompts in yii2How to display error prompts in yii2Apr 18, 2025 pm 11:09 PM

In Yii2, there are two main ways to display error prompts. One is to use Yii::$app-&gt;errorHandler-&gt;exception() to automatically catch and display errors when an exception occurs. The other is to use $this-&gt;addError(), which displays an error when model validation fails and can be accessed in the view through $model-&gt;getErrors(). In the view, you can use if ($errors = $model-&gt;getErrors())

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor