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 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(['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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

With the continuous development of cloud computing technology, data backup has become something that every enterprise must do. In this context, it is particularly important to develop a highly available cloud backup system. The PHP framework Yii is a powerful framework that can help developers quickly build high-performance web applications. The following will introduce how to use the Yii framework to develop a highly available cloud backup system. Designing the database model In the Yii framework, the database model is a very important part. Because the data backup system requires a lot of tables and relationships

As the demand for web applications continues to grow, developers have more and more choices in choosing development frameworks. Symfony and Yii2 are two popular PHP frameworks. They both have powerful functions and performance, but when faced with the need to develop large-scale web applications, which framework is more suitable? Next we will conduct a comparative analysis of Symphony and Yii2 to help you make a better choice. Basic Overview Symphony is an open source web application framework written in PHP and is built on

As the Internet continues to develop, the demand for web application development is also getting higher and higher. For developers, developing applications requires a stable, efficient, and powerful framework, which can improve development efficiency. Yii is a leading high-performance PHP framework that provides rich features and good performance. Yii3 is the next generation version of the Yii framework, which further optimizes performance and code quality based on Yii2. In this article, we will introduce how to use Yii3 framework to develop PHP applications.

The Yii framework is an open source PHP Web application framework that provides numerous tools and components to simplify the process of Web application development, of which data query is one of the important components. In the Yii framework, we can use SQL-like syntax to access the database to query and manipulate data efficiently. The query builder of the Yii framework mainly includes the following types: ActiveRecord query, QueryBuilder query, command query and original SQL query

In the current information age, big data, artificial intelligence, cloud computing and other technologies have become the focus of major enterprises. Among these technologies, graphics card rendering technology, as a high-performance graphics processing technology, has received more and more attention. Graphics card rendering technology is widely used in game development, film and television special effects, engineering modeling and other fields. For developers, choosing a framework that suits their projects is a very important decision. Among current languages, PHP is a very dynamic language. Some excellent PHP frameworks such as Yii2, Ph

If you're asking "What is Yii?" check out my previous tutorial: Introduction to the Yii Framework, which reviews the benefits of Yii and outlines what's new in Yii 2.0, released in October 2014. Hmm> In this Programming with Yii2 series, I will guide readers in using the Yii2PHP framework. In today's tutorial, I will share with you how to leverage Yii's console functionality to run cron jobs. In the past, I've used wget - a web-accessible URL - in a cron job to run my background tasks. This raises security concerns and has some performance issues. While I discussed some ways to mitigate the risk in our Security for Startup series, I had hoped to transition to console-driven commands

With the rapid development of the Internet, APIs have become an important way to exchange data between various applications. Therefore, it has become increasingly important to develop an API framework that is easy to maintain, efficient, and stable. When choosing an API framework, Yii2 and Symfony are two popular choices among developers. So, which one is more suitable for API development? This article will compare these two frameworks and give some conclusions. 1. Basic introduction Yii2 and Symfony are mature PHP frameworks with corresponding extensions that can be used to develop

Yii framework: This article introduces Yii's method of converting objects into arrays or directly outputting them into json format. It has certain reference value and I hope it can help you.
