Home PHP Framework YII How to connect to the database using php yii framework

How to connect to the database using php yii framework

Nov 04, 2019 pm 02:15 PM
yii Connect to the database

This article mainly introduces the database configuration and SQL operation example tutorials in PHP's Yii framework. Yii supports binding a variety of databases. The article mainly gives examples of the use of various query statements in Yii. Need Friends can refer to

How to connect to the database using php yii framework

php yii framework how to connect to the database

Database access ( DAO)

Yii includes a data access layer (DAO) built on PHP PDO. DAO provides a unified API for different databases. ActiveRecord provides databases and models ( M, Model) in MVC, QueryBuilder is used to create dynamic query statements. DAO provides simple and efficient SQL queries, which can be used in various places to interact with the database.

Yii supports the following databases by default ( DBMS):

MySQLMariaDBSQLitePostgreSQLCUBRID: Version>= 9.3. (Due to a bug in the PHP PDO extension, the reference value will be invalid, so you need to use 9.3 on both the client and server side of CUBRID)OracleMSSQL: Version> =2005.

1. Configuration

To start using the database, you first need to configure the database connection component, which is achieved by adding the db component to the application configuration (the "basic" Web application is config/web.php), DSN (Data Source Name) is the data source name, used to specify database information. As shown below:

return [
  // ...
  'components' => [
    // ...
    'db' => [
      'class' => 'yii\db\Connection',
      'dsn' => 'mysql:host=localhost;dbname=mydatabase', // MySQL, MariaDB
      //'dsn' => 'sqlite:/path/to/database/file', // SQLite
      //'dsn' => 'pgsql:host=localhost;port=5432;dbname=mydatabase', // PostgreSQL
      //'dsn' => 'cubrid:dbname=demodb;host=localhost;port=33000', // CUBRID
      //'dsn' => 'sqlsrv:Server=localhost;Database=mydatabase', // MS SQL Server, sqlsrv driver
      //'dsn' => 'dblib:host=localhost;dbname=mydatabase', // MS SQL Server, dblib driver
      //'dsn' => 'mssql:host=localhost;dbname=mydatabase', // MS SQL Server, mssql driver
      //'dsn' => 'oci:dbname=//localhost:1521/mydatabase', // Oracle
      'username' => 'root', //数据库用户名
      'password' => '', //数据库密码
      'charset' => 'utf8',
    ],
  ],
  // ...
];
Copy after login

2. After configuring the connection component, you can use the following syntax to access:

$connection = \Yii::$app->db;
Copy after login

If you want to connect to the database through ODBC, you need to configure the yii\db\Connection::driverName property, for example:

'db' => [
  'class' => 'yii\db\Connection',
  'driverName' => 'mysql',
  'dsn' => 'odbc:Driver={MySQL};Server=localhost;Database=test',
  'username' => 'root',
  'password' => '',
],
Copy after login

If you do not want to define the database connection as a global application component, It can be initialized directly in the code:

$connection = new \yii\db\Connection([
  'dsn' => $dsn,
   'username' => $username,
   'password' => $password,
]);
$connection->open();
Copy after login

3. If you need to perform additional SQL queries after creating the connection, you can add the following code to the application configuration file:

return [
  // ...
  'components' => [
    // ...
    'db' => [
      'class' => 'yii\db\Connection',
      // ...
      'on afterOpen' => function($event) {
        $event->sender->createCommand("SET time_zone = 'UTC'")->execute();
      }
    ],
  ],
  // ...
];
Copy after login

If executing SQL does not return any data, you can use the execute method in the command:

$command = $connection->createCommand('UPDATE post SET status=1 WHERE id=1');
$command->execute();
Copy after login

You can use the insert, update, and delete methods. These methods will generate appropriate SQL based on the parameters and execute it.

// INSERT
$connection->createCommand()->insert('user', [
  'name' => 'Sam',
  'age' => 30,
])->execute();
// INSERT 一次插入多行
$connection->createCommand()->batchInsert('user', ['name', 'age'], [
  ['Tom', 30],
  ['Jane', 20],
  ['Linda', 25],
])->execute();
// UPDATE
$connection->createCommand()->update('user', ['status' => 1], 'age > 30')->execute();
// DELETE
$connection->createCommand()->delete('user', 'status = 0')->execute();
Copy after login

Recommended: "YII Tutorial"

The above is the detailed content of How to connect to the database using php yii framework. For more information, please follow other related articles on the PHP Chinese website!

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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use PHP framework Yii to develop a highly available cloud backup system How to use PHP framework Yii to develop a highly available cloud backup system Jun 27, 2023 am 09:04 AM

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

Symfony vs Yii2: Which framework is better for developing large-scale web applications? Symfony vs Yii2: Which framework is better for developing large-scale web applications? Jun 19, 2023 am 10:57 AM

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

How to read the first few records in a database using PHP? How to read the first few records in a database using PHP? Mar 22, 2024 am 10:03 AM

How to read the first few records in a database using PHP? When developing web applications, we often need to read data from the database and display it to the user. Sometimes, we only need to display the first few records in the database, not the entire content. This article will teach you how to use PHP to read the first few records in the database and provide specific code examples. First, assume that you have connected to the database and selected the table you want to operate on. The following is a simple database connection example:

Data query in Yii framework: access data efficiently Data query in Yii framework: access data efficiently Jun 21, 2023 am 11:22 AM

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

How to use Yii3 framework in php? How to use Yii3 framework in php? May 31, 2023 pm 10:42 PM

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.

Yii2 vs Phalcon: Which framework is better for developing graphics rendering applications? Yii2 vs Phalcon: Which framework is better for developing graphics rendering applications? Jun 19, 2023 am 08:09 AM

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

How to deal with SQLException when connecting to database in Java? How to deal with SQLException when connecting to database in Java? Jun 24, 2023 pm 09:23 PM

In Java programs, connecting to the database is a very common operation. Although ready-made class libraries and tools can be used to connect to the database, various abnormal situations may still occur during program development, among which SQLException is one of them. SQLException is an exception class provided by Java. It describes errors that occur when accessing the database, such as query statement errors, table non-existence, connection disconnection, etc. For Java programmers, especially those using JDBC (Java Data

How to connect to the database in go language How to connect to the database in go language Dec 12, 2023 pm 03:51 PM

Go language connects to the database by importing the database driver, establishing a database connection, executing SQL statements, using prepared statements and transaction processing. Detailed introduction: 1. Import the database driver and use the github.com/go-sql-driver/mysql package to connect to the MySQL database; 2. Establish a database connection and provide the database connection information, including the database address, user name, password, etc. Establish a database connection and so on through the sql.Open function.

See all articles