Welcome Guest, Not a member yet? Register   Sign In
Easy way to Check Database Connection in CodeIgniter
#1

[eluser]Mark LaDoux[/eluser]
I’ve been working on an installer for a CodeIgniter application that I’m building. The thing is, it needs to be database agnostic. If you have seen my previous two CodeIgniter script, you can see that I’ve been boning up on this subject, and now is the time to put it to work. I’ve played around with activerecord, and dborge, and I’ve had some success. With the installer, however, I’ve run into an issue. I need a database agnostic way of checking the connection details without throwing that stupid database error page. I think I found one, utilizing the dbutil class.

Some people might ask me why not just use the conn_id property. Well three reasons, I don’t know if it’s truly database agnostic, I don’t have access to every type of database that CodeIgniter supports, and it doesn’t check to see if the table is there. I could check for the table afterwards, but, that doesn’t really matter at this point. I needed a simple way that would check all three, and this one seems to work so far.

Now, I’m assuming at this point that the database configuration is not yet written, and I don’t want to go through the trouble of having my script edit it before knowing if the database details even work. On the bonus, if db_debug isn’t defined, it defaults to FALSE. I can work with that, and it makes my job easier. For this process I do a couple of things after getting the database details. I override the database configuration file entirely by passing along a DSN string instead. This way, debugging never comes into the picture, and we don’t have to worry about writing the configuration until we know we got all our facts straight. The end result is a script so simple that it must be a sin. Anyway, on with the script:

Code:
// Format DSN
$dsn = 'mysqli://bogus:bogus@localhost';

// Load database and dbutil
$this->load->database($dsn);
$this->load->dbutil();

// check connection details
if(! $this->dbutil->database_exists('bogus'))
{
    // if connection details incorrect show error
    echo 'Incorrect database information provided';
}

That script is just a test script, but it should give developers enough to go on in order to customize it for their own purposes. I could also include the database name in the dsn after a /, but I chose not too as it’s not necessary. It doesn’t effect the result with or without it anyway. What it does is attempt to connect to the database server, load up dbutil, and then checks the database server to see if the requested database exists on it. If any part of this operation fails, you’ll get the error. Anyway, have fun, and I hope this helps you out on a project of your own.
#2

[eluser]goFrendiAsgard[/eluser]
Unfortunately dbutil->database_exists() doesn't work with pdo




Theme © iAndrew 2016 - Forum software by © MyBB