In our project, we may sometimes need to connect more than one database, how to implement it in CI?
We have created two new databases locally, as follows:
Modify the configuration file database.php file to the following format (readers modify the configuration of the corresponding parameters according to their own database):
<?phpdefined (' BasePath ') or exit (' No Direct script access allowed ');/*| -------------------------------------------------------------------| DATABASE CONNECTIVITY settings| -------------------------------------------------------------------| This file would contain the settings needed to access your database.| | For complete instructions consult the ' Database Connection ' | Page of the User guide.| | -------------------------------------------------------------------| Explanation of variables| -------------------------------------------------------------------|| [' DSN '] The full DSN string describe a connection to the database.| [' hostname '] The hostname of your database server.| [' username '] The username used to connect to the database| [' Password '] The password used to connect to the database| [' Database '] The name of the database want to connect to| [' Dbdriver '] The database driver. e.g.: mysqli.| Currently supported:| Cubrid, IBase, MSSQL, MySQL, mysqli, oci8,| ODBC, PDO, POStgre, SQLite, Sqlite3, sqlsrv| [' Dbprefix '] You can add an optional prefix, which'll be added| To the table name when using the Query Builder class| [' Pconnect '] True/false-whether to use a persistent connection| [' Db_debug '] True/false-whether database errors should be displayed.| [' cache_on '] True/false-enables/disables Query Caching| [' Cachedir '] The path to the folder where the cache files should is stored| [' Char_set '] The character set used in communicating with the database| [' Dbcollat '] The character collation used in communicating with the database| Note:for MySQL and Mysqli databases, this setting are only used| As a backup if your server is running PHP < 5.2.3 or MySQL < 5.0.7| (and in table creation queries made with DB Forge). | There is a incompatibility in PHP with mysql_real_escape_string () which| Can make your site vulnerable to SQL injection if you are using a| Multi-Byte Character set and is running versions lower than these.| Sites using Latin-1 or UTF-8Database character set and collation are unaffected.| [' Swap_pre '] A default table prefix that should is swapped with the dbprefix| [' Encrypt '] Whether or not to use an encrypted connection.| [' Compress '] Whether or not to use client compression (MySQL only) | [' Stricton '] True/false-forces ' Strict Mode ' connections|-good for ensuring Strict SQL while Developing| [' Failover '] array-a array with 0 or more data for connections if the main should fail.| [' Save_queries '] True/false-whether to ' save ' all executed queries.| Note:disabling This would also effectively disable both| $this->db->last_query () and profiling of DB queries.| When you run a query, with the setting set to TRUE (default), | CodeIgniter would store the SQL statement for debugging purposes.| However, this could cause high memory usage, especially if you run| A lot of SQL queries ... disable this to avoid that problem.| | The $active _group variable lets you choose which connection group to| Make active. By default therE is only one group (the ' default ' group). The $query _builder variables lets you determine whether or not to load| The Query Builder class.*/$active _group = ' test ';//default connection Test Database $active_record = true;//Open active record$db[' test ') = Array (' dsn ' = ' = ', ' hostname ' = ' localhost ', ' username ' = ' root ', ' password ' + ' ', ' ' database ' = ' test ', ' Dbdriver ' + ' mysqli ', ' dbprefix ' + ', ' pconnect ' and ' = False, ' db_debug ' = TRUE, ' cache_on ' = False, ' Cachedir ' + ', ' char_set ' = ' utf8 ', ' dbcollat ' = ' utf8_general_ci ', ' swap_pre ' = ', ' encrypt ' and ' = FALSE ', ' Compress ' = False, ' Stricton ' = False, ' failover ' = = Array (), ' save_queries ' = TRUE);//test2 database-related configuration $db[' Test2 '] = Array (' DSN ' = = ', ' hostname ' = ' localhost ', ' username ' = ' root ', ' password ' = ' = ', ' = ') ' Test2 ', ' dbdriver ' = ' mysqli ', ' dbprefix ' = ', ' pconnect ' = False, ' db_debug ' = TRUE, ' cache_on ' = False , ' cachedir ' = ', ' char_set ' = ' utf8 ', ' Dbcollat '= ' utf8_general_ci ', ' swap_pre ' + ', ' encrypt ' and false, ' compress ' and false, ' stricton ' = False, ' Failover ' = = Array (), ' save_queries ' = TRUE);
Create two files in the Applicaton/model directory: score.php
<?phpclass Score extends Ci_model { private $tableName = ' score '; function __construct () { parent::__construct (); } Public Function Getallscores () { return $this->db->get ($this->tablename);} }
and students.php
<?phpclass Students extends Ci_model { private $tableName = ' Students '; function __construct () { parent::__construct (); } Public Function getallstudents () { return $this->db->get ($this->tablename);} }
To modify the Welcome controller:
<?phpdefined (' BasePath ') or exit (' No Direct script access allowed '); class Welcome extends Ci_controller {/** * Index Pa GE for this controller. * Maps to the following URL * http://example.com/index.php/welcome *-OR-* http://example.com/index.php/welcome/index *-OR-* Since This controller is set as the default controller in * config/routes.php, it's displayed at Http://example. com/* * So no other public methods not prefixed with an underscore would * map to/index.php/welcome/<method_name> * @see http://codeigniter.com/user_guide/general/urls.html */public function __construct () {parent::__construct (); $ This->load->model (' students '); $this->load->model (' score ');} Public Function Index () {Var_dump ($this->students->getallstudents ()->result ()) Var_dump ($this->score- >getallscores ()->result ());d ie (' End of Test ');}}
To access the http://localhost/ci2/address, the browser output looks like this:
You can see that CI did not find the score table and we need to use it in the score.php file
$this->db = $this->load->database (' test2 ', TRUE);
Displays the database that indicates where the score is located:
<?phpclass Score extends Ci_model { private $tableName = ' score '; Private $db; function __construct () { parent::__construct (); $this->db = $this->load->database (' test2 ', TRUE); } Public Function Getallscores () { return $this->db->get ($this->tablename);} }
To access the http://localhost/ci2/address again, the output is as follows:
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
CI Advanced usage Link multiple databases