


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!

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

The following steps can be used to resolve the problem that Navicat cannot connect to the database: Check the server connection, make sure the server is running, address and port correctly, and the firewall allows connections. Verify the login information and confirm that the user name, password and permissions are correct. Check network connections and troubleshoot network problems such as router or firewall failures. Disable SSL connections, which may not be supported by some servers. Check the database version to make sure the Navicat version is compatible with the target database. Adjust the connection timeout, and for remote or slower connections, increase the connection timeout timeout. Other workarounds, if the above steps are not working, you can try restarting the software, using a different connection driver, or consulting the database administrator or official Navicat support.

Common problems and solutions for Hadoop Distributed File System (HDFS) configuration under CentOS When building a HadoopHDFS cluster on CentOS, some common misconfigurations may lead to performance degradation, data loss and even the cluster cannot start. This article summarizes these common problems and their solutions to help you avoid these pitfalls and ensure the stability and efficient operation of your HDFS cluster. Rack-aware configuration error: Problem: Rack-aware information is not configured correctly, resulting in uneven distribution of data block replicas and increasing network load. Solution: Double check the rack-aware configuration in the hdfs-site.xml file and use hdfsdfsadmin-printTopo

Redis memory soaring includes: too large data volume, improper data structure selection, configuration problems (such as maxmemory settings too small), and memory leaks. Solutions include: deletion of expired data, use compression technology, selecting appropriate structures, adjusting configuration parameters, checking for memory leaks in the code, and regularly monitoring memory usage.

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

Permissions issues and solutions for MinIO installation under CentOS system When deploying MinIO in CentOS environment, permission issues are common problems. This article will introduce several common permission problems and their solutions to help you complete the installation and configuration of MinIO smoothly. Modify the default account and password: You can modify the default username and password by setting the environment variables MINIO_ROOT_USER and MINIO_ROOT_PASSWORD. After modification, restarting the MinIO service will take effect. Configure bucket access permissions: Setting the bucket to public will cause the directory to be traversed, which poses a security risk. It is recommended to customize the bucket access policy. You can use MinIO

Redis memory fragmentation refers to the existence of small free areas in the allocated memory that cannot be reassigned. Coping strategies include: Restart Redis: completely clear the memory, but interrupt service. Optimize data structures: Use a structure that is more suitable for Redis to reduce the number of memory allocations and releases. Adjust configuration parameters: Use the policy to eliminate the least recently used key-value pairs. Use persistence mechanism: Back up data regularly and restart Redis to clean up fragments. Monitor memory usage: Discover problems in a timely manner and take measures.
