ThinkPHP连接数据库及主从数据库的设置教程
发布人:shili8
发布时间:2022-12-07 03:38
阅读次数:29
本文较为详细的讲述了thinkphp连接数据库及主从数据库的设置方法,在thinkphp项目开发中非常实用。具体实现方法如下:
一、项目根目录上建立config.php
代码如下所示:
<?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',// 数据库端口
);
?>
二、设置项目配置文件
\home\conf\config.php文件代码如下:
<?php
$arr1=array{
'url_model'=>2, //pathinfo访问模式
};
$arr2=include './config.php';
return array_merge($arr1,$arr2); //数组整合
?>
\admin\conf\config.php文件代码如下:
<?php
$arr1=array{
'url_model'=>1, //普通访问模式 get方式
};
$arr2=include './config.php';
return array_merge($arr1,$arr2); //数组整合
?>
三、主从数据库设置
该设置比较适合高并发,高负载的大型网站
读者可以到\thinkphp\common\convention.php中查看默认的系统常量设置
config.php文件设置如下:
<?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,//读写分离,默认第一台服务器为写入服务器,其它的只读取不写入 ); ?>
在某个action中读取数据库文件参数:
$hh=c('db_host'); //c可以读取配置文件中的值
$pp=c('db_prefix');
$this->assain('h',$hh);
$this->assain('p',$pp);
$this->display();
这个action下的tpl:
数据库服务器地址:{$h}
数据库表前缀:{$p}
希望本文所述方法对大家的thinkphp程序设计能有所帮助。

