Love Fuel?    Donate

FuelPHP Forums

Ask your question about FuelPHP in the appropriate forum, or help others by answering their questions.
How can we connect to a newly created database?
  • Hello,

    I would like to do the following things in a task,  but I couldn't find a way to do...
    - drop database
    - create database
    - run migration

    My code is below


    \Database_connection::instance()->disconnect();
    \DBUtil::drop_database('db_name');
    \DBUtil::create_database('db_name');
    \Database_connection::instance()->connect();
    \Migrate::latest();


    It seems dropping and creating database worked fine, but can't connect the newly created db again. Is there a way to re-connect the database?









  • HarroHarro
    Accepted Answer
    If "db_name" is the database you have defined as your default database in db.php, you don't need to connect, the first DB call would automatically connect for you.

    If it is not your default database, but another named database definition in your db.php, you can do:

    \Config::load('migrations', true);
    \Config::set('migrations.connection', 'db_name');
    Migrate::latest();

    If "db_name" is a random name, things get a bit more tricky.
  • Thanks for your comment.

    > If "db_name" is the database you have defined as your default database in db.php, you don't need to connect, the first DB call would automatically connect for you.

    Yes I use 'db_name' as the default database, but the below didn't work for me.
    \DBUtil::drop_database('db_name');
    \DBUtil::create_database('db_name');
    \Migrate::latest();

    I tried this code and worked like a charm.

    \DBUtil::drop_database('db_name');
    \DBUtil::create_database('db_name');
    \DB::query("USE db_name;")->execute();
    \Migrate::latest('default', 'app', true);
    "db_name" is used as default.app.

  • HarroHarro
    Accepted Answer
    I can imagine that without the disconnect it will not work, since the selected database context is lost after you dropped it.

    But if you disconnect after creating the database again, the Migrate call should reconnect, and since the database does exist again, it should set the correct context without having to select it.

    But your solution works too, great find!
  • Many thanks! The way you suggested also works fine!

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

In this Discussion