I do a command like this:

$db = new \yii\db\Connection([ 'dsn' => 'mysql:host=localhost;dbname=cms', 'username' => 'root', 'password' => '', 'charset' => 'utf8', ]); db()->createCommand("UPDATE `cms_profile` SET `UserName`='$model->Fname $model->Lname',`Mobile1`=$model->Mobile,`Mail`='$model->Mail',`ProfileImg`='db.jpg' WHERE `Mail`='$this->Mail'")->execute(); 

How to use the native connection to the database specified in the framework config instead of creating the $ db object?

  • Yii::$app->db->createCommand()->execute() or are you Yii::$app->db->createCommand()->execute() about? yiiframework.com/doc-2.0/… - Roman Grinyov
  • This is what I had in mind, I tried it that way, it says a scolding that such a method was not found. I have yii2 basic can therefore? - perfect
  • No, not because ... Which method was not found: createCommand() ? - Roman Grinyov
  • one
    I found a mistake, made a typo, everything works, you are right to do so, make your comment a reply for the correct answer. - perfect

1 answer 1

From the documentation :

Since the connection to the database is often needed in several places, a common practice is to configure it as an application component:

 return [ // ... 'components' => [ // ... 'db' => [ 'class' => 'yii\db\Connection', 'dsn' => 'mysql:host=localhost;dbname=example', 'username' => 'root', 'password' => '', 'charset' => 'utf8', ], ], // ... ]; 

Therefore, since this is a component of the application, we can access it like this:

 Yii::$app->db 

In your case, the code will look like this:

 Yii::$app->db->createCommand(<SQL-запрос>)->execute()