Yasar Arafath
Yasar Arafath

Reputation: 625

How to create database in Yii2 format

I want create database with yii2.

$servername = "localhost";
$username = "username";
$password = "password";

// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Create database
$sql = "CREATE DATABASE myDB";
if ($conn->query($sql) === TRUE) {
    echo "Database created successfully";
} else {
    echo "Error creating database: " . $conn->error;
}

$conn->close();

With this code we can create DB but i want to know whether it is possible in Yii2 manner

Upvotes: 2

Views: 3304

Answers (2)

Prabowo Murti
Prabowo Murti

Reputation: 1341

Currently there is no way you can do it with Yii2. It is because too much complexity for a framework to have everything works on many database engines (MySQL, Oracle, MSSQL, etc). Too many efforts to code, yet the functionality can be done using your query.

IMO, there is nothing wrong with creating a database using current db connection. This can be found in SaaS multi-tenant architecture, when a new client registers an account, then a new separated DB created to encapsulate mostly everything / security reason.

Upvotes: 1

Amit Verma
Amit Verma

Reputation: 779

It's not recommended to create tables at run-time. Already set-up the schema and run your SQL / non-SQL query.

For this, you need to create a file (say myDB.php) in your config folder and provide database details as follows :

<?php

return [
    'class' => 'yii\db\Connection',
    'dsn' => 'dblib:host=localhost;dbname=yourDBName',
    'username' => 'yourUsername',
    'password' => 'yourPassword',
    'charset' => 'utf8',
];

Register this database in your web.php.Add following line :

'my_db' => require(__DIR__ . '/myDB.php'),

In controller, use this db as follows :

$query = 'select columnID from table where ID=:ID';
Yii::$app->my_db->createCommand($query)
                ->bindValue(':ID',1)
                ->queryOne();

Upvotes: 0

Related Questions