ThinkPHP-Multi-database interactive communication

Source: Internet
Author: User
The following example shows how to copy data from one database to another. 1, in config. configure useful database information in php // source database & quot; DB_DSN1 & quot; & gt; & quot; mysql ://...

The following example shows how to copy data from one database to another.

1. configure the useful database information in config. php.

  1. // Source database
  2. "DB_DSN1" => "mysql: // user name: password @ database Address: Port/database name ",
  3. // Target database
  4. "DB_DSN2" => "mysql: // user name: password @ database Address: Port/database name ",
  5. // Example:
  6. "DB_DSN1" => "mysql: // user: 123@127.0.0.1: 3306/db1 ",

2. usage

1) retrieve configuration information from config. php

$ Dsn1 = C ('Db _ DSN1 ');

$ Dsn2 = C ("DB_DSN2 ");

2) define a model

$ Model = new Model ();

$ Model-> db ("1", $ dsn1); // define the model as dsn1 by default.

3) define the source data table to be queried

$ Table = $ model-> db ("1")-> table ('name of the queried table ');

$ Data = $ table-> where (query condition)-> select ();

4) store the source database data to the target data table

  1. Foreach ($ data as $ val ){
  2. $ Model-> db ("2", $ dsn2)-> query ("SET FOREIGN_KEY_CHECKS = 0 ;");
  3. // Save
  4. $ Rev = $ model-> db ("2", $ dsn2)-> table ($ table)-> where ($ mWhere)-> save ($ val );
  5. // Add
  6. // $ Rev = $ model-> db ("2", $ dsn2)-> table ($ table)-> add ($ val );
  7. }
  8. // The operation above directs the database to the target database again
  9. // You can also use this query $ model-> db ("2", $ dsn2)-> query ("SET FOREIGN_KEY_CHECKS = 0 ;");

The preceding four steps allow different databases to switch back and forth.

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.