thinkphp implementing multi-database operations

Source: Internet
Author: User

This article mainly introduces the thinkphp implementation of multi-database connection solution, the need for friends can refer to the following

When thinkphp implements multiple data connections, it is only necessary to define the model if the database is in the same server:

?
123 classMembersModel extends Model{protected $trueTableName= ‘members.members‘; //数据库名.表名(包含了前缀)}

Then it can be like D ("members"); This instantiates the model and operates like a normal model.
But later found his database in two different servers, so the above method is not.
At this point, we need to use the majority of TP connection characteristics.

After reviewing the official documentation for testing and correcting it, the following solutions were obtained:

To establish a multi-data connection, you first construct the database configuration parameters. But if you build a database configuration array every time you build a multi-database connection, it can be cumbersome, rather than written in a configuration file. It's a bit tricky to write here.

?
123456789101112131415161718192021222324252627282930313233343536373839404142434445 <?php$configarray(‘DEBUG_MODE‘=>true,‘default_module‘=>‘Index‘,‘ROUTER_ON‘=>TRUE,‘DATA_RESULT_TYPE‘=>1,‘SHOW_RUN_TIME‘=>true,      // 运行时间显示‘SHOW_ADV_TIME‘=>true,      // 显示详细的运行时间‘SHOW_DB_TIMES‘=>true,      // 显示数据库查询和写入次数‘SHOW_CACHE_TIMES‘=>true,    // 显示缓存操作次数‘SHOW_USE_MEM‘=>true,      // 显示内存开销‘HTML_FILE_SUFFIX‘=>‘.shtml‘,   // 默认静态文件后缀‘HTML_CACHE_ON‘=>false,     // 默认关闭静态缓存‘HTML_CACHE_TIME‘=>60,     // 静态缓存有效期‘HTML_READ_TYPE‘=>1,      // 静态缓存读取方式 0 readfile 1 redirect‘HTML_URL_SUFFIX‘=>‘.shtml‘// 伪静态后缀设置//默认数据库链接‘DB_TYPE‘=>‘mysql‘,‘DB_HOST‘=>‘localhost‘,‘DB_NAME‘=>‘news‘,‘DB_USER‘=>‘root‘,‘DB_PWD‘=>‘123‘,‘DB_PORT‘=>‘3306‘,‘DB_PREFIX‘=>‘news_‘,//我的第一个数据库连接‘DB_BBS‘=>array(‘dbms‘ => ‘mysql‘,‘username‘ => ‘discuz‘,‘password‘ => ‘123‘,‘hostname‘ => ‘localhost‘,‘hostport‘ => ‘3306‘,‘database‘ => ‘discuz‘),//第二个数据库链接,‘DB_NEWS‘=>array(‘dbms‘=>‘mysql‘,‘username‘=>‘root‘,‘password‘=>‘123‘,‘hostname‘=>‘localhost‘,‘hostport‘=>‘3306‘,‘database‘=>‘news‘));return $config;?>

So we can use C ("Db_bbs") and C ("Db_news") to get the configuration array of the database.
Configured, you now need to instantiate the model. Because our model needs to use two different database connections, the project configuration file default database configuration, if you build a table model such as UserModel.class.php,
If you use D ("user"), you will get an error if you do not have a user table in the current default database. So we're going to build an empty model. An empty model does not choose a table.
There are two ways to build an empty model. $dao =d (); and $dao=new Model (); all can.

?
1 $dao=D();

After instantiating the model, we need to increase the database model;

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

Say this addconnect (); The prototype of this function is different in 1.0.3 and 1.0.4.
The prototypes in 1.0.3 are:

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

The prototypes in 1.0.4 are:

?
1 boolean addConnect (mixed $config, mixed $linkNum)

A third parameter is missing.
The first parameter is the configuration array of the database, the second parameter is the number of the added connection, and the number is the connection that is given when the connection to the database is switched. Note the built-in database connection sequence number is 0, so additional database connection numbers should start at 1. The third parameter is true if two databases are the same connection;

Once you have added the database connection, you can switch the database connection at any time. For example, we're going to use db_news this database, so write:

?
1 $dao->switchConnect(2);

Because this is just a connection to the database, and there is no table selected, the next option is to select a table.
Note that the table name here is the full name, which is the table prefix plus the table name. Because we do not have a prefix in the configuration array of the connection database. I think I should be able to define, but I don't know. Now that's it.

?
1 $dao->table("cdb_members");

You can then use the model like a normal model.
For example, I want to query all the information of the user who passed the ID:

?
12 $map=array("id"=>$_GET["id"]);$res=$dao->find($map);

You can see if the query was successful.

?
1 dump($res);

If you want to use the table of the Db_bbs database now, just switch the connection again;

?
1 $dao->switchConnect(2);

Then select the table query. Remember, you must select the table again after you switch the model, or you will get an error.
And then you can do it like a normal model.
Here are some of the problems that are present in the manual:

1. A non-empty model was established when instantiating a multi-database connection. (It seems to have been wrongly written.) This can be an error. It is suggested to establish an empty model;
2.addConnect () parameters are different in different versions, not written in the manual;
3. The empty model needs to be selected after the establishment of the table, this manual does not.

For the above points, thinkphp users can adjust according to the different versions as appropriate.

thinkphp implementing multi-database operations

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.