CodeIgniter : use Database Forge to test if DB exists

2k Views Asked by At

I'm using CodeIgniter 3.1.0 to develop an app. In order to improve its installation, I've written an Install_Controller, and an Install_Model. I'm using Database Forge class to manage the database. Thanks to it, I can create a DB, but I can't check before if it exists. Actually, my idea was to pass a query to dbforge, like "CREATE DATABASE IF NOT EXISTS mydatabase". I've search the doc but there wasn't any function that could meet my requirements. Where can I write such a query ?

Here is an excerpt from the former :

$this->load->model('Install_Model');
$this->Install_Model->launchInstall();

Here is the code of the latter :

class Install_Model extends CI_Model {

    public function __construct()   {

        parent::__construct();

            $this->load->dbforge();

    }

    public function index() {

        if ($this->dbforge->create_database('mydatabase')) 
        {
            echo "OK";
        }

        else {

            echo "Error somewhere";
        }

        $this->load->database('mydatabase');
    }

}
1

There are 1 best solutions below

3
On

you can use this custom SQL query function within your installation script to create new database.

public function createDB($databse) {
    $strSQL = "CREATE DATABASE IF NOT EXISTS $databse";
    $query = $this->db->query($strSQL);
   if (!$query) {
      throw new Exception($this->db->_error_message(),
      $this->db->_error_number());
                return FALSE;
            } else {
                return TRUE;
            }

}