Search code examples
phpdatabasefuelphp

Create database if not exist in FuelPHP


First of all I don't have any database and I write code in migrations to create database, table and data, I want to check if database not exist then auto create new database have name in db connect and try catch this connect if error.

public function up()
{
    try {
        \DBUtil::create_database('database_name', 'utf8_general_ci', true);
        // the true flag adds a IF NOT EXISTS
    } catch(\Database_Exception $e) {
        echo $e->getMessage();
    }
}

try code but give error "Unknown database database_name" when I run "php oil refine migrate" in commandline

Can I try catch custom exception this error?

1049!

Fuel\Core\Database_Exception [ 1049 ]:
SQLSTATE[HY000] [1049] Unknown database 'database_name'

Solution

  • Creating a database is not something that is usually done by migrations as it would tie you in to using the same DB name all the time, if you are deploying multiple sites on the same server or have a similar scenario this becomes a big problem.

    It's generally assumed that the database itself has been created as part of the set-up, either manual or automatic, so is available for PHP to connect to.