This article mainly introduces how ThinkPHP connects to the database and sets the master-slave database. it is a useful technique for large-scale web project development, for more information about how to connect ThinkPHP to the database and set the master and slave databases, ThinkPHP is very useful in ThinkPHP project development. The specific implementation method is as follows:
1. create config. php in the project Root Directory
The code is as follows:
<? Php if (! Defined ('think _ path') exit (); return array ('Db _ type' => 'mysql ', // Database type 'DB _ host' => 'localhost', // HOST 'DB _ name' => 'aoli ', // database name 'DB _ user' => 'root', // database username 'DB _ pwd' => '', // database password 'DB _ prefix' => '', // data table PREFIX 'DB _ charset' => 'utf8 ', // website code 'DB _ port' => '123', // database PORT);?>
2. set the project configuration file
The code for the \ Home \ Conf \ config. php file is as follows:
<? Php $ arr1 = array {'URL _ model' => 2, // pathinfo access mode}; $ arr2 = include '. /config. php '; return array_merge ($ arr1, $ arr2); // array integration?>
The code for the \ Admin \ Conf \ config. php file is as follows:
<? Php $ arr1 = array {'URL _ model' => 1, // get mode in normal access mode}; $ arr2 = include '. /config. php '; return array_merge ($ arr1, $ arr2); // array integration?>
III. master/slave database settings
This setting is suitable for large websites with high concurrency and high load.
You can view the default system constant settings in \ ThinkPHP \ Common \ convention. php.
The config. php file is set as follows:
<? Php return array (// 'config map '=> 'configuration value' // backend 'URL _ mode' => 0, 'DB _ type' => 'mysql ', 'db _ host' => 'localhost, 192.168.1.2 ', // Two database servers 'DB _ port' => '123 ', 'db _ name' => 'thinkphptest', // if the database NAME is the same, you do not need to define multiple, if they are different from those on the server, they correspond to 'DB _ user' => 'root', 'DB _ pwd' => 'password ', // table PREFIX 'DB _ prefix' => 'think _ ', // Configure the master-slave database 'DB _ DEPLOY_TYPE' => 1, // enable the distributed database 'DB _ RW_SEPARATE '=> ture, // read/write splitting. by default, the first server is the write server, and the others only read and write data.);?>
Read database file parameters in an action:
$ Hh = C ('Db _ host'); // C can read the value $ pp = C ('Db _ prefix') in the configuration file '); $ this-> assain ('H', $ hh); $ this-> assain ('P', $ pp); $ this-> display ();
Tpl under this action:
Database server address: {$ h} database table prefix: {$ p}
I hope this method will be helpful for ThinkPHP programming.