CodeIgniter Forums
Create database on first Migration - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5)
+--- Forum: Libraries & Helpers (https://forum.codeigniter.com/forumdisplay.php?fid=11)
+--- Thread: Create database on first Migration (/showthread.php?tid=65723)



Create database on first Migration - joelrlneto - 07-16-2016

Hello, everyone.

Is there a way to create the database by runing a migration in the application startup? In this case I want to create the main application's database, not a secondary one, that is, my first migration will be responsible to create the database.

I'm coming from .NET and I used to use Entity Framework Migration to handle all the database 'actions', like creating and updating it. In the first execution, if the database do not exists, EF Migrations creates it for me.

I tried to create a migration to do it, but to make it work I first need to configure the database connection on config/database.php, seting the database name. But I do not have a database initially! I want the migrations create it for me.

Thank you all. =)


RE: Create database on first Migration - InsiteFX - 07-16-2016

You would need to use the low level MySQLi class to do this.

PHP Code:
<?php

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

// Create connection
$conn_id = new mysqli($servername$username$password);

// Check connection
if ($conn_id->connect_error)
{
 
   exit("Connection failed: " $conn_id->connect_error);


// Create database
$sql "CREATE DATABASE database_name";

if (
$conn_id->query($sql) === TRUE)
{
 
   echo "Database created successfully";
}
else
{
 
   echo "Error creating database: " $conn_id->error;
}

$conn_id->close();

?>



RE: Create database on first Migration - joelrlneto - 07-19-2016

Thank you, InsiteFX. I thought that could exist a "more beautiful" way to do it just using migrations, but I see that there's not.
So, I'll continue creating my database manually and letting the tables' creations for the migrations.
=)