Home >PHP Framework >YII >How to obtain sql statement in yii2?

How to obtain sql statement in yii2?

angryTom
angryTomOriginal
2020-01-25 00:08:236166browse

Yii2 is a high-performance component-based PHP framework. Using Yii2 can conveniently operate the database. Below we introduce the method of yii2 to obtain the current SQL statement. We hope it will be helpful to students who are learning the yii framework!

How to obtain sql statement in yii2?

How does yii2 obtain the sql statement?

When we use YII2 to develop a project, we will check the currently executed SQL statement to troubleshoot errors. So how does YII2 obtain the current SQL statement?

We can use getRawSql() to obtain the current sql statement. The usage examples are as follows:

举例:UserModel
$query = UserModel::find()->where(['status'=>1]);
echo $query->createCommand()->getRawSql();

Knowledge supplement

yii2 Use createCommand() to add, delete, modify and check

Query a single piece of data

$sql = "SELECT `name` FROM `table` WHERE id='7'";
$users=Yii::$app->db->createCommand($sql)->queryOne();

Query multiple pieces of data

$sql = "SELECT `name` FROM `table` WHERE name='$name'";
$users=Yii::$app->db->createCommand($sql)->queryAll();

Modify data

Yii::$app->db->createCommand()->update('table', ['name' => $name], "id = {$id}")->execute();
//update 第一个参数:表名 第二个参数 :要修改为的数据 第三个数据:修改条件

Add data

Yii::$app->db->createCommand()->insert("table",array("name"=>'zhangsan',"age"=>'18'));
//insert 第一个参数:表名 第二个参数 :要添加的数据

Delete data

Yii::$app->db->createCommand()->delete('table', 'age = 30')->execute();
//delete 第一个参数:表名 第二个参数 :删除的条件

Recommended related articles and tutorials: yii tutorial

The above is the detailed content of How to obtain sql statement in yii2?. 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