search
HomeBackend DevelopmentPHP TutorialHow to solve the problem of multi-database connection in ThinkPHP

How to solve the problem of multi-database connection in ThinkPHP

Jul 03, 2018 pm 05:27 PM
thinkphpMultiple database connectionsSolution

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

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How do you create and use an interface in PHP?How do you create and use an interface in PHP?Apr 30, 2025 pm 03:40 PM

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

What is the difference between crypt() and password_hash()?What is the difference between crypt() and password_hash()?Apr 30, 2025 pm 03:39 PM

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.

How can you prevent Cross-Site Scripting (XSS) in PHP?How can you prevent Cross-Site Scripting (XSS) in PHP?Apr 30, 2025 pm 03:38 PM

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

What is autoloading in PHP?What is autoloading in PHP?Apr 30, 2025 pm 03:37 PM

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.

What are PHP streams?What are PHP streams?Apr 30, 2025 pm 03:36 PM

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.

What is the maximum size of a file that can be uploaded using PHP ?What is the maximum size of a file that can be uploaded using PHP ?Apr 30, 2025 pm 03:35 PM

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.

What is Nullable types in PHP ?What is Nullable types in PHP ?Apr 30, 2025 pm 03:34 PM

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

What is the difference between the unset() and unlink() functions ?What is the difference between the unset() and unlink() functions ?Apr 30, 2025 pm 03:33 PM

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

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Safe Exam Browser

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

WebStorm Mac version

Useful JavaScript development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool