Generate DB From Mysqldump if Not Exists for Codeigniter

Nowadays there’s Laravel, giving us ways to migrate our db everywhere we place our code, making things simpler and faster to work! Unfortunately, Laravel requires at least Php 5.3 and if you are like me using CI with older Php versions you may also want that CI automatically generates the db for you, based in a mysql dump for example!

There’s quiet a lot of ways to do it, but I found out that this way is quiet fast, so you may want to try it.

  1. Set a location with your mysql dump, into a local directory for the project, such as:
$mysqldumplocation = "/path/to/mysqldump/myFileName.sql";
  1. In your database.php configuration file, after setting up your connectivity settings add the following code:
// check if db exists
mysql_connect(
    $db['default']['hostname'],
    $db['default']['username'],
    $db['default']['password']
);
$mysqli = new mysqli(
    $db['default']['hostname'],
    $db['default']['username'],
    $db['default']['password']
);

if (!$mysqli->select_db($db['default']['database'])) {

    $mysqli->query( "CREATE DATABASE ".$db['default']['database'] );
    $mysqli->select_db($db['default']['database']);
    $mysqli->multi_query( file_get_contents( $mysqldumplocation );
};

Obs: You can have different database connectivity settings based in your custom environment variable in your apache or other that you desire, such has $SERVER[‘SERVERADDR’] or $SERVER[‘HOSTNAME’], for example:

if(isset($_SERVER['ENVIRONMENT']) && $_SERVER['ENVIRONMENT'] == 'development'){

    $db['default']['hostname'] = "hostname";
    $db['default']['username'] = "username";
    $db['default']['password'] = "password";

} else {

    $db['default']['hostname'] = "hostname";
    $db['default']['username'] = "username";
    $db['default']['password'] = "password";

};

Enjoy!

comments powered by Disqus