php – Is it possible to create a database from under yii2


I got this task:

Implement the following functionality in yii or yii2: 3) Write a class for interaction with the database (preferably postgreSQL), implement methods for the class:

  • Create – creates a database, input parameters, table name, and an array consisting of the field name, field data type, add. Field data (not null, primary key for example).

Now I can’t understand with my mind how to do this from under yii2. Indeed, in the yii2 settings, the used database is already indicated in the config, and it is not clear to me how to create a new database, because this requires root rights to the DBMS.

The question is: I do not understand the task or the task itself is not feasible?


I understand that I was late with an answer, but I will answer. The fact that in the config when connecting, we specify the name of the database in the DSN, it just says that this is the default database for the application and does not in any way prohibit us from working with other databases until they are created.

Let's see an example DSN

$db = [
    'class' => 'yii\db\Connection',
    'dsn' => 'mysql:host=localhost;dbname=db1',
    'username' => 'root',
    'password' => '',
    'charset' => 'utf8',

We tell the application to connect to db1 by default. But what prevents us from making such a request from the application?

FROM db1.users 
JOIN db2.firms ON db1.users.firm_id =

A table from another database will be connected and the query will succeed. The main thing is that you have enough rights.

We can also create, for example, a migration of the following type


use yii\db\Migration;

class m170219_083615__ extends Migration
    public function up()
        $this->execute("CREATE DATABASE test2");

And this migration will be successful too. The main thing is that our current user has rights to create databases.

Scroll to Top