Connecting to your Database

If only some of your pages require database connectivity you can manually connect to your database by adding this line of code in any function where it is needed, or in your class constructor to make the database available globally in that class.

$this->database();

If the above function does not contain any information in the first parameter it will connect to the group specified in your database config file. For most people, this is the preferred method of use.

Manually Connecting to a Database

To choose a specific group from your config file you can do this:

$this->database('group_name');

Where group_name is the name of the connection group from your config file.

To connect manually to a desired database you can pass an array of values:

$config['hostname'] = 'localhost';
$config['username'] = 'myusername';
$config['password'] = 'mypassword';
$config['database'] = 'mydatabase';
$config['driver']   = 'mysqli';

$this->database($config);

For information on each of these values please see the configuration page.

Connecting to Multiple Databases

If you need to connect to more than one database simultaneously you can do so as follows:

$this->database('group_one');
$this->database('group_two');

Note: Change the words “group_one” and “group_two” to the specific group names you are connecting to (or you can pass the connection values as indicated above).

Reconnecting / Keeping the Connection Alive

If the database server’s idle timeout is exceeded while you’re doing some heavy PHP lifting (processing an image, for instance), you should consider pinging the server by using the reconnect() method before sending further queries, which can gracefully keep the connection alive or re-establish it.

$this->db->reconnect();

Manually closing the Connection

While Codingox intelligently takes care of closing your database connections, you can explicitly close the connection.

$this->db->close();