search
HomeBackend DevelopmentPHP TutorialThinkPHP connection database and master-slave database setting tutorial, thinkphp master-slave_PHP tutorial

ThinkPHP connection database and master-slave database setting tutorial, thinkphp master-slave

This article describes in detail how to connect ThinkPHP to the database and set up the master-slave database, which is very practical in ThinkPHP project development. The specific implementation method is as follows:

1. Create config.php in the project root directory

The code is as follows:

<&#63;php
 if(!defined('THINK_PATH')) exit();
 return array(
  'DB_TYPE'    =>  'mysql',// 数据库类型  
  'DB_HOST'    =>  'localhost',// 主机
  'DB_NAME'    =>  'aoli',// 数据库名称
  'DB_USER'    =>  'root',// 数据库用户名
  'DB_PWD'     =>  '',// 数据库密码
  'DB_PREFIX'   =>  '',// 数据表前缀
  'DB_CHARSET'   =>  'utf8',// 网站编码
  'DB_PORT'    =>  '3306',// 数据库端口
 );
&#63;>

2. Set project configuration file

HomeConfconfig.php file code is as follows:

<&#63;php
 $arr1=array{
  'URL_MODEL'=>2, //pathinfo访问模式
 };
 $arr2=include './config.php';
 return array_merge($arr1,$arr2); //数组整合
&#63;>

AdminConfconfig.php file code is as follows:

<&#63;php
 $arr1=array{
  'URL_MODEL'=>1, //普通访问模式 get方式
 };
 $arr2=include './config.php';
 return array_merge($arr1,$arr2); //数组整合
&#63;>

3. Master-slave database settings

This setting is more suitable for large websites with high concurrency and high load
Readers can check the default system constant settings in ThinkPHPCommonconvention.php

The config.php file settings are as follows:

<&#63;php
  return array(
  //'配置项'=>'配置值'
  //后台
  'URL_MODE'=>0,
  'DB_TYPE'=>'mysql',
  'DB_HOST'=>'localhost,192.168.1.2',//两台数据库服务器
  'DB_PORT'=>'3306',
  'DB_NAME'=>'thinkphptest',//如果数据库名相同,不用定义多个,如果不相同与服务器依次对应
  'DB_USER'=>'root',
  'DB_PWD'=>'password',
  //表前缀
  'DB_PREFIX'=>'think_',
  //接下来配置主从数据库
  'DB_DEPLOY_TYPE'=>1,//开启分布式数据库
  'DB_RW_SEPARATE'=>ture,//读写分离,默认第一台服务器为写入服务器,其它的只读取不写入
  );
&#63;>

Read database file parameters in an action:

  $hh=C('DB_HOST'); //C可以读取配置文件中的值
  $pp=C('DB_PREFIX');
  $this->assain('h',$hh);
  $this->assain('p',$pp);
  $this->display();

tpl under this action:

  数据库服务器地址:{$h}
  数据库表前缀:{$p}

I hope the method described in this article will be helpful to everyone’s ThinkPHP programming design.

Can there be multiple types of thinkphp master-slave database?

As far as I know. You can set up multiple databases, but there is no way you can set them up. . . .

Reading the help documentation will help you. , the help document should have this multi-database setting. .

How to connect to the database in ThinkPHP [Repost]

How to connect to the database in ThinkPHP. Before operating the database, we need to create a Model. Before talking about Model and Action, let me first explain the storage locations of Model and Action. Model is saved in the lib/Model folder in the program directory, and Action is saved in the lib/Action folder in the program directory. The default Model rules of the ThinkPHP system are as follows: the civil name of the Model file is similar to "Model class name+Model.class.php, and the default operating database table name of the Model is DB_PREFIX+Model class name we defined in config.php. Model class names and file names need to be capitalized." In the Model file, define a class and extend the Model class. The general writing method is as follows: class class name Model extends Model{} So, now let's define a Model. Since the name of our database table is cms_article, the class ArticleModel extends Model{} file is saved as ArticleModel.class.php. There is no need to write anything, a Model has been defined. So now, let's continue our Action knowledge. Many rules of Action and Model are very similar. The difference is that Action does not directly operate the database, but needs to operate the database through Model. Now we define an Action to complete the operation. class IndexAction extends Action{function index(){$Article = D("Article");}} Save the file as IndexAction.class.php. OK, now let's refresh the homepage. If there are no prompts, congratulations. The database connection Model and Action definition are all normal. The D method in Action is to call Model, and Article is the Model class in ArticleModel.class.php that we just defined~ In other words, while defining Model, we have completed the connection to the database and preparation for database table operations~

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/868235.htmlTechArticleThinkPHP connection database and master-slave database setting tutorial, thinkphp master-slave article describes in detail ThinkPHP connection database and How to set up the master-slave database, open in ThinkPHP project...
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
What is the difference between unset() and session_destroy()?What is the difference between unset() and session_destroy()?May 04, 2025 am 12:19 AM

Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

What is sticky sessions (session affinity) in the context of load balancing?What is sticky sessions (session affinity) in the context of load balancing?May 04, 2025 am 12:16 AM

Stickysessionsensureuserrequestsareroutedtothesameserverforsessiondataconsistency.1)SessionIdentificationassignsuserstoserversusingcookiesorURLmodifications.2)ConsistentRoutingdirectssubsequentrequeststothesameserver.3)LoadBalancingdistributesnewuser

What are the different session save handlers available in PHP?What are the different session save handlers available in PHP?May 04, 2025 am 12:14 AM

PHPoffersvarioussessionsavehandlers:1)Files:Default,simplebutmaybottleneckonhigh-trafficsites.2)Memcached:High-performance,idealforspeed-criticalapplications.3)Redis:SimilartoMemcached,withaddedpersistence.4)Databases:Offerscontrol,usefulforintegrati

What is a session in PHP, and why are they used?What is a session in PHP, and why are they used?May 04, 2025 am 12:12 AM

Session in PHP is a mechanism for saving user data on the server side to maintain state between multiple requests. Specifically, 1) the session is started by the session_start() function, and data is stored and read through the $_SESSION super global array; 2) the session data is stored in the server's temporary files by default, but can be optimized through database or memory storage; 3) the session can be used to realize user login status tracking and shopping cart management functions; 4) Pay attention to the secure transmission and performance optimization of the session to ensure the security and efficiency of the application.

Explain the lifecycle of a PHP session.Explain the lifecycle of a PHP session.May 04, 2025 am 12:04 AM

PHPsessionsstartwithsession_start(),whichgeneratesauniqueIDandcreatesaserverfile;theypersistacrossrequestsandcanbemanuallyendedwithsession_destroy().1)Sessionsbeginwhensession_start()iscalled,creatingauniqueIDandserverfile.2)Theycontinueasdataisloade

What is the difference between absolute and idle session timeouts?What is the difference between absolute and idle session timeouts?May 03, 2025 am 12:21 AM

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

What steps would you take if sessions aren't working on your server?What steps would you take if sessions aren't working on your server?May 03, 2025 am 12:19 AM

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

What is the significance of the session_start() function?What is the significance of the session_start() function?May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

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

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools