


How to solve the problem of multi-database connection in ThinkPHP
This article mainly introduces the solution of ThinkPHP to realize multi-database connection. Friends who need it can refer to it
When ThinkPHP realizes the connection of multiple data, if the database is in the same server, then only this is needed Define the model:
class MembersModel extends Model{ protected $trueTableName = 'members.members'; //数据库名.表名(包含了前缀) }
Then you can instantiate the model like D("Members"); and operate like a normal model.
But later it was discovered that his databases were on two different servers, so the above method would not work.
At this time, you need to use the multi-data connection feature of TP.
In this regard, after consulting the official documentation for testing and correction, we came up with the following solution:
To establish a multi-data connection, you must first construct the database configuration parameters. But if you create a database configuration array every time you establish a multi-database connection, it will be very troublesome. It is better to write it in the configuration file. How to write here still requires some skills.
<?php $config= array( '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; ?>
At this point we can use C ("DB_BBS") and C ("DB_NEWS") to get the database configuration array.
After configuration, now we need to instantiate the model. Because our model needs to use two different database connections, the project configuration file defaults to a database configuration. If you create a model of a certain table such as UserModel.class.php,
If you use D(" User"); but if there is no User table in the current default database, an error will be reported. So we're going to build an empty model. Empty models will not select tables.
There are two ways to create an empty model. Both $dao=D(); and $dao=new Model(); are OK.
$dao=D();
After instantiating the model, we need to add a database model;
$dao->addConnect(C("DB_BBS"),1,true); $dao->addConnect(C("DB_NEWS"),2,true);
said Take a look at addConnect(); the prototype of this function is different between 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 configuration array of the database, and the second parameter is the number of the added connection. This number needs to be given as the serial number of the connection when switching the database connection. NoteThe built-in database connection serial number is 0, so the additional database connection serial number should start from 1. The third parameter is if the two databases are the same connection, it is true;
After adding the database connection, you can switch the database connection at any time. For example, if we want to use the DB_NEWS database, we can write it like this:
$dao->switchConnect(2);
Because the connection to the database is only established here and no table is selected, so the next step is to Select table.
Note that the table name here is the full name, that is, the table prefix plus the table name. Because we have no prefix in the configuration array for connecting to the database. I think it should be definable, but I don't know. That's it for now.
$dao->table("cdb_members");
After that, you can use this model like a normal model.
For example, if I want to query all the information of the user with the passed ID:
$map=array("id"=>$_GET["id"]); $res=$dao->find($map);
I can see if the query is successful.
dump($res);
If you want to use the DB_BBS database table now, you only need to switch the connection again;
$dao->switchConnect(2);
Then select the table query. Remember, you must select the table again after switching models, otherwise an error will occur.
After that, it can be operated like a normal model.
The following points out several problems in the manual:
1. A non-empty model is established when instantiating a multi-database connection. (It seems that I wrote it wrong.) This may make mistakes. It is recommended to establish an empty model;
2. The parameters of addConnect() are different in different versions and are not listed in the manual;
3. After establishing an empty model, you need to select a table, which is not included in this manual.
In view of the above points, ThinkPHP users can make corresponding adjustments according to different versions.
The above is the entire content of this article. I hope it will be helpful to everyone’s study. For more related content, please pay attention to the PHP Chinese website!
Related recommendations:
ThinkPHP implements ajax-like official website search function
php float intercepts floating-point characters without rounding String method
The above is the detailed content of How to solve the problem of multi-database connection in ThinkPHP. For more information, please follow other related articles on the PHP Chinese website!

The article explains how to create, implement, and use interfaces in PHP, focusing on their benefits for code organization and maintainability.

The article discusses the differences between crypt() and password_hash() in PHP for password hashing, focusing on their implementation, security, and suitability for modern web applications.

Article discusses preventing Cross-Site Scripting (XSS) in PHP through input validation, output encoding, and using tools like OWASP ESAPI and HTML Purifier.

Autoloading in PHP automatically loads class files when needed, improving performance by reducing memory use and enhancing code organization. Best practices include using PSR-4 and organizing code effectively.

PHP streams unify handling of resources like files, network sockets, and compression formats via a consistent API, abstracting complexity and enhancing code flexibility and efficiency.

The article discusses managing file upload sizes in PHP, focusing on the default limit of 2MB and how to increase it by modifying php.ini settings.

The article discusses nullable types in PHP, introduced in PHP 7.1, allowing variables or parameters to be either a specified type or null. It highlights benefits like improved readability, type safety, and explicit intent, and explains how to declar

The article discusses the differences between unset() and unlink() functions in programming, focusing on their purposes and use cases. Unset() removes variables from memory, while unlink() deletes files from the filesystem. Both are crucial for effec


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

WebStorm Mac version
Useful JavaScript development tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool
