PDO method (suitable for multi-table connection queries). (Recommended learning: yii framework)
$sql = "";//原生态sql语句 xx::model()->dbConnection->createCommand($sql)->execute(); 非select语句(update、insert、delete) xx::model()->dbConnection->createCommand($sql)->queryRow(); 查询select一条记录 xx::model()->dbConnection->createCommand($sql)->queryAll(); 查询select多条记录 $sql = "select a.*, count(b.role_id)as num from {{user_role}} a left join {{user}} b on a.id = b.role_id group by b.role_id order by a.id"; $user_role_info = UserRole::model()->dbConnection->createCommand($sql)->queryAll(); $this->render("list", array('user_role_info'=>$user_role_info));
For example
$sql = "select a.*, count(b.role_id)as num from slgo_user_role a left join slgo_user b on a.id = b.role_id group by b.role_id order by a.id"; $user_role_info = UserRole::model()->dbConnection->createCommand($sql)->queryAll(); $this->render("list", array('user_role_info'=>$user_role_info));
Active Record method
(1)New
$post=new Post; $post->title='sample post'; $post->content='post body content'; $post->save();
Criteria method
You can also use $condition to specify more complex query conditions. Instead of using strings, we can make $condition an instance of CDbCriteria, which allows us to specify conditions that are not limited to WHERE.
$criteria=new CDbCriteria; $criteria->select='title'; // 只选择 'title' 列 $criteria->condition='postID=:postID'; $criteria->params=array(':postID'=>10); $post=Post::model()->find($criteria);
An alternative to CDbCriteria is to pass an array to the find method. The keys and values of the array respectively correspond to the attribute names and values of the criterion
The above example can be rewritten as follows:
$post=Post::model()->find(array( 'select'=>'title', 'condition'=>'postID=:postID', 'params'=>array(':postID'=>10), ));
When a query condition is about pressing When the specified value matches several columns, we can use findByAttributes(). We make the $attributes parameter an array of values indexed by column names.
In some frameworks, this task can be achieved by calling a method like findByNameAndTitle.
Although this approach looks tempting, it often causes confusion, conflicts and issues such as case sensitivity of column names.
Query Builder method
$user = Yii::app()->db->createCommand() ->select('id, username, profile') ->from('tbl_user u') ->join('tbl_profile p', 'u.id=p.user_id') ->where('id=:id', array(':id'=>$id)) ->queryRow();
1. When making good use of ActiveRecord, that is, do not let it generate the second SQL query method. From my experience, do not overdo it. Pay attention to the difference in time and performance. For big data queries, in terms of memory space, you can use toArray() in yii2 to save memory consumption.
2. The advantage of ActiveRecord over PDO lies in its convenience.
One is that compared to writing SQL statements, using ActiveRecord is simpler, and more importantly, it is less error-prone.
Second, it provides many conveniences beyond SQL statements, such as parameter filtering, binding, etc. You will always encounter this in web development. Writing one SQL statement after another, the degree of code reuse is not high, and it is easy to forget to filter somewhere, causing security risks.
3. Yii2 already has Query, which is better in performance than ActiveRecord and can be used as a replacement. Of course, convenience and efficiency are two sides of the coin, and its use is not as convenient as ActiveRecord.
But my experience in the project is that Query is only used slightly less frequently than ActiveRecord. Personally, I think Query/ActiveQuery is an exciting new feature introduced in Yii2.
4. The previous articles talk about the application scenarios of ActiveRecord. For PDO, if you want to use it, it should be for more complex SQL operations, such as one or two sentences that cannot be written clearly.
In this case, using ActiveRecord to build is no less complex than writing SQL directly, so you can consider using PDO. But in my impression, if the SQL statements used in the project are very complex, they will be written as DB Views or stored procedures. Therefore, I feel that PDO is not used much, it can be said to be very little.
5. If we pursue higher efficiency, I personally don’t think PDO should be used too much, which makes later maintenance extremely difficult. Instead, you can consider optimizing SQL queries, optimizing indexes and table structures, using cache, etc. It is worth mentioning that using cache is the simplest, most direct, and most effective method.
6. There is never any need to consider performance issues prematurely
The above is the detailed content of There are several ways to connect to the database in yii. For more information, please follow other related articles on the PHP Chinese website!

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.

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

With the continuous development of PHP framework technology, Yi2 and TP5 have attracted much attention as the two mainstream frameworks. They are all known for their outstanding performance, rich functionality and robustness, but they have some differences and advantages and disadvantages. Understanding these differences is crucial for developers to choose frameworks.

Abstract of the first paragraph of the article: When choosing software to develop Yi framework applications, multiple factors need to be considered. While native mobile application development tools such as XCode and Android Studio can provide strong control and flexibility, cross-platform frameworks such as React Native and Flutter are becoming increasingly popular with the benefits of being able to deploy to multiple platforms at once. For developers new to mobile development, low-code or no-code platforms such as AppSheet and Glide can quickly and easily build applications. Additionally, cloud service providers such as AWS Amplify and Firebase provide comprehensive tools

The Yi2 Rate Limiting Guide provides users with a comprehensive guide to how to control the data transfer rate in Yi2 applications. By implementing rate limits, users can optimize application performance, prevent excessive bandwidth consumption and ensure stable and reliable connections. This guide will introduce step-by-step how to configure the rate limit settings of Yi2, covering a variety of platforms and scenarios to meet the different needs of users.

Article Summary: Yii Framework is an efficient and flexible PHP framework for creating dynamic and scalable web applications. It is known for its high performance, lightweight and easy to use features. This article will provide a comprehensive tutorial on the Yii framework, covering everything from installation to configuration to development of applications. This guide is designed to help beginners and experienced developers take advantage of the power of Yii to build reliable and maintainable web solutions.

This article introduces the latest tutorial on calling public functions, which is implemented in Easy Language (Yi) language. For beginners, easy-to-language programming languages are easy to learn, and this article provides a detailed step-by-step guide to help users master how to call public functions in Yi applications. By following this tutorial, users will learn how to define, load, and call common functions, thereby enhancing their code reusability and flexibility.

Yii2 is a powerful PHP framework that has been widely praised by developers. With its high performance, scalability and user-friendly interface, it becomes ideal for building large, complex web applications. However, like any framework, Yii2 has some advantages and disadvantages to consider.


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

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

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

Dreamweaver Mac version
Visual web development tools

WebStorm Mac version
Useful JavaScript development tools

Zend Studio 13.0.1
Powerful PHP integrated development environment