ThinkPHP multi-database connection Solution

Source: Internet
Author: User
This article describes how ThinkPHP implements multi-database connection.

This article describes how ThinkPHP implements multi-database connection.

When ThinkPHP connects multiple data items, if the database is on the same server, you only need to define the model as follows:

Class MembersModel extends Model {protected $ trueTableName = 'members. members '; // database name. Table name (including the prefix )}

Then you can instantiate the model like D ("Members") and operate it like a normal model.
But later I found that his database was on two different servers, so the above method would not work.
At this time, we need to use the multi-data connection feature of TP.

In this regard, refer to the official documentation for testing and rectification, and then come up with the following solutions:

To establish a multi-data connection, you must first construct database configuration parameters. However, if the database configuration array is set up every time a multi-database connection is established, it will be very troublesome. It is better to write it in the configuration file. It still requires some skills to write data here.

<? Php $ config = array ('debug _ mode' => true, 'default _ module' => 'index', 'router _ on' => TRUE, 'Data _ RESULT_TYPE '=> 1, 'show _ RUN_TIME' => true, // display 'show _ adv_time' => true, // display the detailed running time 'show _ DB_TIMES '=> true, // display the number of database queries and writes 'show _ CACHE_TIMES' => true, // display the cache operation count 'show _ USE_MEM '=> true, // display the memory overhead 'html _ FILE_SUFFIX' => '.shtml ', // The default static file suffix 'html _ CACHE_ON '=> false, // The default static file suffix 'html _ CACHE_TIME' => 60, // static cache validity period: 'html _ READ_TYPE '=> 1 ,/ /Static cache read mode 0 readfile 1 redirect 'html _ URL_SUFFIX '=> '.shtml ', // set the pseudo-static suffix // default database link 'db _ type' => 'mysql', 'db _ host' => 'localhost ', 'db _ name' => 'News', 'db _ user' => 'root', 'db _ pwd' => '123 ', 'db _ port' => '123', 'db _ prefix' => 'news _', // my first database connection 'db _ BBS '=> array ('dbms' => 'mysql', 'username' => 'discuz ', 'Password' => '000000', 'hostname' => 'localhost', 'hostport' => '000000', 'database' => 'discuz '), // link to the second database, 'db _ News' => array ('Dbms '=> 'mysql', 'username' => 'root', 'Password' => '000000', 'hostname' => 'localhost ', 'hostport' => '123', 'database' => 'News'); return $ config;?>

Now we can use C ("DB_BBS") and C ("DB_NEWS") to obtain the Database Configuration array.
After configuration, You need to instantiate the model. Because our model requires two different databases to be connected, the project configuration file contains a database configuration by default. If you have created a table model such as UserModel. class. php,
If you use D ("User"), but if there are no User tables in the current default database, an error is returned. Therefore, we need to create an empty model. Empty models do not select tables.
There are two ways to create an empty model. $ Dao = D (); and $ dao = new Model.

$ Dao = D ();

After the model is instantiated, we need to add a database model;

$ Dao-> addConnect (C ("DB_BBS"), 1, true); $ dao-> addConnect (C ("DB_NEWS"), 2, true );

Let's talk about this addConnect (); the prototype of this function is different in 1.0.3 and 1.0.4.
The prototype in 1.0.3 is:

Boolean addConnect (mixed $ config, mixed $ linkNum, [boolean $ eqType = true])

The prototype in 1.0.4 is:

Boolean addConnect (mixed $ config, mixed $ linkNum)

The third parameter is missing.
The first parameter is the database configuration array, and the second parameter is the number of the added connection. When switching the database connection, you must provide the connection with the serial number. Note that the built-in database connection sequence number is 0, so the additional database connection sequence number should start from 1. The third parameter is true if the two databases have the same connection;

After adding a database connection, you can switch the database connection at any time. For example, if we want to use the database DB_NEWS, we should write it like this:

$ Dao-> switchConnect (2 );

Because the database connection is established and no table is selected, You need to select the table next.
Note that the table name is the full name, that is, the table prefix and table name. Because we do not have a prefix in the database connection configuration array. I think it can be defined, but I don't know. This is now the case.

$ Dao-> table ("cdb_members ");

Then you can use this model like a normal model.
For example, I want to query all the information of the user with the passed ID:

$ Map = array ("id" = >$ _ GET ["id"]); $ res = $ dao-> find ($ map );

Check whether the query is successful.

Dump ($ res );

If you want to use the database table of DB_BBS, you only need to switch the connection again;

$ Dao-> switchConnect (2 );

Then select the table for query. Remember, you must select another table after switching the model. Otherwise, an error will occur.
Then you can operate like a normal model.
The following issues exist in the manual:

1. A non-empty model is created when multiple database connections are instantiated. (It seems that I still wrote an error .) This may cause errors. We recommend that you create an empty model;
2. The parameters of addConnect () are different in different versions and are not written in the manual;
3. Select a table after an empty model is created. This Manual does not contain this table.

ThinkPHP users can make corresponding adjustments based on different versions.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.