You are currently browsing Crystal’s documentation for the 0.4 version - Switch to version: 0.3
Connection manager
From the beginning Crystal was designed to work with multiple database connections. In this chapter you will learn how to create and work with database connections in Crystal.
If you don't provide any parameters in the db() function, Crystal will try to connect to the database using the configuration file in /path_to_crystal/config/database.php and the parameters with 'default' key
$db['default']['username'] = "username"; $db['default']['password'] = "pass"; $db['default']['database'] = "database"; $db['default']['driver'] = "mysql"; $db['default']['char_set'] = "utf8"; $db['default']['dbcollat'] = "utf8_general_ci"; $db = Crystal::db();
Multiple connections
You can create and use multiple database connections by creating configuration arrays with different keys, using the prototype
described in the Configuration chapter
For example:
$db['production']['username'] = "username";
$db['production']['password'] = "pass";
$db['production']['database'] = "database";
$db['production']['driver'] = "mysql";
$db['production']['char_set'] = "utf8";
$db['production']['dbcollat'] = "utf8_general_ci";
// Can be accessed like this:
$db = Crystal::db('production');
Connection arrays
Sometimes you don't have access to the database configuration file. For example if you want to create some installation scripts it is very hard to manipulate and extend files. For occasions like this one you can write all your database details in a simple PHP array:
$db_config = array( 'username' => 'username', 'password'=> 'password', 'database' => 'database_name', 'driver' => 'mysql' ); $db = Crystal::db($db_config);
Dynamic configuration files
As long as you write the configuration files using the default prototype, Crystal will give you the freedom to save them anywhere you want. For example in this tutorial I use the configuration file from Codeigniter.
$db = Crystal::db('path_to_configuration_file');
// If you have this configuration file
$db['development']['username'] = "username";
$db['development']['password'] = "pass";
$db['development']['database'] = "database";
$db['development']['driver'] = "mysql";
$db['development']['char_set'] = "utf8";
$db['development']['dbcollat'] = "utf8_general_ci";
$db['production']['username'] = "username";
$db['production']['password'] = "pass";
$db['production']['database'] = "database";
$db['production']['driver'] = "mysql";
$db['production']['char_set'] = "utf8";
$db['production']['dbcollat'] = "utf8_general_ci";
// You can define your configuration keys by adding second parameter to the db function:
$db = Crystal::db('path_to_configuration_file', 'development');
$db = Crystal::db('path_to_configuration_file', 'production');