ThinkPHP Connection Database and Master Slave Database Setting Tutorial

  • 2021-07-13 04:56:10
  • OfStack

This paper describes the ThinkPHP connection database and master-slave database setting method in detail, which is very practical in ThinkPHP project development. The specific implementation method is as follows:

1. Create config. php on the project root directory

The code looks like this:


<?php
 if(!defined('THINK_PATH')) exit();
 return array(
  'DB_TYPE'    =>  'mysql',//  Database type   
  'DB_HOST'    =>  'localhost',//  Host 
  'DB_NAME'    =>  'aoli',//  Database name 
  'DB_USER'    =>  'root',//  Database user name 
  'DB_PWD'     =>  '',//  Database password 
  'DB_PREFIX'   =>  '',//  Datasheet prefix 
  'DB_CHARSET'   =>  'utf8',//  Web site coding 
  'DB_PORT'    =>  '3306',//  Database port 
 );
?>

2. Set up the project profile

The code for the\ Home\ Conf\ config. php file is as follows:


<?php
 $arr1=array{
  'URL_MODEL'=>2, //pathinfo Access mode 
 };
 $arr2=include './config.php';
 return array_merge($arr1,$arr2); // Array integration 
?>

The code for the\ Admin\ Conf\ config. php file is as follows:


<?php
 $arr1=array{
  'URL_MODEL'=>1, // Normal access mode  get Mode 
 };
 $arr2=include './config.php';
 return array_merge($arr1,$arr2); // Array integration 
?>

3. Master-slave database setup

This setting is more suitable for large websites with high concurrency and high load
Readers can view the default system constant settings in\ ThinkPHP\ Common\ convention. php

The config. php file is set as follows:


<?php
  return array(
  //' Configuration item '=>' Configuration value '
  // Backstage 
  'URL_MODE'=>0,
  'DB_TYPE'=>'mysql',
  'DB_HOST'=>'localhost,192.168.1.2',// Two database servers 
  'DB_PORT'=>'3306',
  'DB_NAME'=>'thinkphptest',// If the database names are the same, you don't need to define multiple ones. If they are different, they correspond to the servers in turn 
  'DB_USER'=>'root',
  'DB_PWD'=>'password',
  // Table prefix 
  'DB_PREFIX'=>'think_',
  // Next, configure the master-slave database 
  'DB_DEPLOY_TYPE'=>1,// Open a distributed database 
  'DB_RW_SEPARATE'=>ture,// Read-write separation, default 1 One server is a write server, and others only read but not write 
  );
?>

Read database file parameters in an action:


  $hh=C('DB_HOST'); //C You can read values from configuration files 
  $pp=C('DB_PREFIX');
  $this->assain('h',$hh);
  $this->assain('p',$pp);
  $this->display();

tpl under this action:


   Database server address: {$h}
   Database table prefix: {$p}

I hope the method described in this paper can be helpful to everyone's ThinkPHP programming.


Related articles: