Understanding ThinkPHP Query Method and Database Connection Initialization
The article explains how ThinkPHP’s query method works with raw SQL, distinguishes between execute for writes and query for reads, details MySQL master‑slave replication considerations, and describes the framework’s database connection initialization, including read/write separation logic and related code examples.
When using native SQL statements in ThinkPHP, write operations should use execute while read operations should use query.
MySQL master‑slave replication relies on MySQL’s own mechanism, and replication latency must be optimized because excessive delay affects both business logic and user experience.
In ThinkPHP, the core class Thinkphp/library/Model.class.php defines a query method that internally calls Thinkphp/library/Think/Db/Driver/Mysql.class.php.
/**
* SQL查询
* @access public
* @param string $sql SQL
* @param mixed $parse 是否需要解析SQL
* @return mixed
*/
public function query($sql,$parse=false) {
if(!is_bool($parse) && !is_array($parse)) {
$parse = func_get_args();
array_shift($parse);
}
$sql = $this->parseSql($sql,$parse);
return $this->db->query($sql);
}The query method in the MySQL driver executes the SQL, records execution time, handles errors, and returns the result set.
/**
* 执行查询 返回数据集
* @access public
* @param string $str sql指令
* @return mixed
*/
public function query($str) {
if(0===stripos($str, 'call')){ // 存储过程查询支持
$this->close();
$this->connected = false;
}
$this->initConnect(false);
if (! $this->_linkID) return false;
$this->queryStr = $str;
if ($this->queryID) { $this->free(); }
N('db_query',1);
G('queryStartTime');
$this->queryID = mysql_query($str, $this->_linkID);
$this->debug();
if (false === $this->queryID) {
$this->error();
return false;
} else {
$this->numRows = mysql_num_rows($this->queryID);
return $this->getAll();
}
}During database initialization, initConnect(false) is called, which means the read side of a read/write‑separated setup is used; passing true would force a connection to the master server.
/**
* 初始化数据库连接
* @access protected
* @param boolean $master 主服务器
* @return void
*/
protected function initConnect($master=true) {
if(1 == C('DB_DEPLOY_TYPE'))
$this->_linkID = $this->multiConnect($master);
else {
if (! $this->connected) $this->_linkID = $this->connect();
}
}
/**
* 连接分布式服务器
* @access protected
* @param boolean $master 主服务器
* @return void
*/
protected function multiConnect($master=false) {
foreach ($this->config as $key=>$val){
$_config[$key] = explode(',',$val);
}
if(C('DB_RW_SEPARATE')){
if($master) {
$r = floor(mt_rand(0, C('DB_MASTER_NUM')-1));
} else {
if(is_numeric(C('DB_SLAVE_NO'))) {
$r = C('DB_SLAVE_NO');
} else {
$r = floor(mt_rand(C('DB_MASTER_NUM'), count($_config['hostname'])-1));
}
}
} else {
$r = floor(mt_rand(0, count($_config['hostname'])-1));
}
$db_config = array(
'username' => isset($_config['username'][$r])?$_config['username'][$r]:$_config['username'][0],
'password' => isset($_config['password'][$r])?$_config['password'][$r]:$_config['password'][0],
'hostname' => isset($_config['hostname'][$r])?$_config['hostname'][$r]:$_config['hostname'][0],
'hostport' => isset($_config['hostport'][$r])?$_config['hostport'][$r]:$_config['hostport'][0],
'database' => isset($_config['database'][$r])?$_config['database'][$r]:$_config['database'][0],
'dsn' => isset($_config['dsn'][$r])?$_config['dsn'][$r]:$_config['dsn'][0],
'params' => isset($_config['params'][$r])?$_config['params'][$r]:$_config['params'][0],
'charset' => isset($_config['charset'][$r])?$_config['charset'][$r]:$_config['charset'][0],
);
return $this->connect($db_config,$r);
}The query method’s second parameter defaults to false for read operations; write‑related methods such as delete, save, and add in Thinkphp/library/Model.class.php use true to force master‑server execution.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
