ThinkPHP5 动态连接数据库 - 01

MySQL :

CREATE DATABASE IF NOT EXISTS `db1` DEFAULT CHARACTER SET utf8 ;
USE `db1`;

CREATE TABLE IF NOT EXISTS `think_data`(
`user_id` INT(8) UNSIGNED NOT NULL AUTO_INCREMENT,
`user_name` VARCHAR(255) NOT NULL COMMENT '名称',
PRIMARY KEY (`user_id`)  ) ENGINE=INNODB  DEFAULT CHARSET=utf8 ;

INSERT  INTO `think_data`(`user_id`,`user_name`)
VALUES (1,'Tim'),(2,'Jason'),(3,'Tom'),(4,'Jack'),(5,'Frank'),(6,'Tina'),(7,'Suman'),(8,'Linda');


CREATE DATABASE IF NOT EXISTS `db2` DEFAULT CHARACTER SET utf8 ;
USE `db2`;

CREATE TABLE IF NOT EXISTS `think_data`(
`user_id` INT(8) UNSIGNED NOT NULL AUTO_INCREMENT,
`user_name` VARCHAR(255) NOT NULL COMMENT '名称',
PRIMARY KEY (`user_id`)  ) ENGINE=INNODB  DEFAULT CHARSET=utf8 ;

INSERT  INTO `think_data`(`user_id`,`user_name`)
VALUES (10,'Rainly'),(11,'Sunny');


apps/config.php :

// 数据库配置1
    'db1' => [
        // 数据库类型
        'type' => 'mysql',
        // 服务器地址
        'hostname' => '127.0.0.1',
        // 数据库名
        'database' => 'db1',
        // 数据库用户名
        'username' => 'root',
        // 数据库密码
        'password' => '123456',
        // 数据库连接端口
        'hostport' => '3306',
        // 数据库连接参数
        'params' => [],
        // 数据库编码默认采用utf8
        'charset' => 'utf8',
        // 数据库表前缀
        'prefix' => 'think_',
        // 开启数据库调试
        'debug'  =>  true,
    ],
    // 数据库配置2
    'db2' => [
        // 数据库类型
        'type' => 'mysql',
        // 服务器地址
        'hostname' => '127.0.0.1',
        // 数据库名
        'database' => 'db2',
        // 数据库用户名
        'username' => 'root',
        // 数据库密码
        'password' => '123456',
        // 数据库连接端口
        'hostport' => '3306',
        // 数据库连接参数
        'params' => [],
        // 数据库编码默认采用utf8
        'charset' => 'utf8',
        // 数据库表前缀
        'prefix' => 'think_',
    ],


apps/apps/index/controller/User.php :

<?php
namespace app\index\controller;
use think\Controller;
use think\Request;
use think\Db;

class User extends Controller
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {

        $result1 = Db::connect('db1')->query('select * from think_data where user_id = 2');
        $result2 = Db::connect([
            // 数据库类型
            'type' => 'mysql',     // 服务器地址
            'hostname' => '127.0.0.1',     // 数据库名
            'database' => 'db2',     // 用户名
            'username' => 'root',     // 密码
            'password' => '123456',
            // 开启调试模式
            'debug' => true,])->query('select * from think_data where user_id = 10');
        $result3 = Db::connect('db1')->query('select * from think_data where user_id = 3');

        dump($result1);
        dump($result2);
        dump($result3);
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {

    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {

    }

    /**
     * 显示指定的资源
     *
     * @param  int  $user_id
     * @return \think\Response
     */
    public function read($user_id)
    {

    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $user_id
     * @return \think\Response
     */
    public function edit($user_id)
    {

    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $user_id
     * @return \think\Response
     */
    public function update(Request $request, $user_id)
    {

    }

    /**
     * 删除指定资源
     *
     * @param  int  $user_id
     * @return \think\Response
     */
    public function delete($user_id)
    {

    }

    public function miss()
    {

    }
}


路由配置apps/route.php :
<?php
use think\Route;
//主表路由(分组路由配置顺序必须是从表路由优先配置,否则从表路由一直会路由到主表控制器的方法上)
Route::group(['name'=>'users','prefix'=>'index/User/'], function() {
    Route::get('create$','create',['merge_extra_vars'=>true]);
    Route::post('/$','save',['merge_extra_vars'=>true]);
    Route::get(':user_id/edit$','edit',['merge_extra_vars'=>true]);
    Route::get(':user_id$','read',['merge_extra_vars'=>true]);
    Route::put(':user_id$','update',['merge_extra_vars'=>true]);
    Route::delete(':user_id$','delete',['merge_extra_vars'=>true]);
    Route::get('/$','index',['merge_extra_vars'=>true]);
    Route::miss('miss'); // 在根资源路由里面写miss路由
}, [], ['user_id' => '\d+']);

// create GET  http://contoso.org/users/create
// save   POST http://contoso.org/users
// edit   GET  http://contoso.org/users/10/edit
// read   GET  http://contoso.org/users/10
// update PUT  http://contoso.org/users/10
// delete DELETE http://contoso.org/users/10
// index  GET  http://contoso.org/users



路由地址:http://contoso.org/users

浏览器 OUTPUT :

/home/myth/www/think/thinkphp/library/think/Debug.php:165:
array (size=1)
  0 =>
    array (size=2)
      'user_id' => int 2
      'user_name' => string 'Jason' (length=5)

/home/myth/www/think/thinkphp/library/think/Debug.php:165:
array (size=1)
  0 =>
    array (size=2)
      'user_id' => int 10
      'user_name' => string 'Rainly' (length=6)

/home/myth/www/think/thinkphp/library/think/Debug.php:165:
array (size=1)
  0 =>
    array (size=2)
      'user_id' => int 3
      'user_name' => string 'Tom' (length=3)



    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {

        $result1 = Db::connect('mysql://root:[email protected]:3306/db1#utf8')->query('select * from think_data where user_id = 2');
        $result2 = Db::connect('mysql://root:[email protected]:3306/db2#utf8')->query('select * from think_data where user_id = 10');
        $result3 = Db::connect('mysql://root:[email protected]:3306/db1#utf8')->query('select * from think_data where user_id = 3');

        dump($result1);
        dump($result2);
        dump($result3);
    }

ThinkPHP5 动态连接数据库 - 01