本代碼是從uchome的代碼修改的
封裝的方式比較簡單
為了方便
希望給有需要的朋友帶來幫助
PHP實現的Mysql讀寫分離
主要特性
英文比較爛
php code for mysql read/write split
feature:
simply rw split
one master
support all mysql feature
link to the master and slave at the same time
PHP代碼
mysql_rw_php
<?php
/****************************************
*** mysql
*** code by hqlulu#gmail
***
***
*** code modify from class_mysql
****************************************/
class mysql_rw_php {
//查詢個數
var $querynum =
//當前操作的數據庫連接
var $link = null;
//字符集
var $charset;
//當前數據庫
var $cur_db =
//是否存在有效的只讀數據庫連接
var $ro_exist = false;
//只讀數據庫連接
var $link_ro = null;
//讀寫數據庫連接
var $link_rw = null;
function mysql_rw_php(){
}
function connect($dbhost
if($pconnect) {
if(!$this
$halt && $this
}
} else {
if(!$this
$halt && $this
}
}
//只讀連接失敗
if(!$this
//未初始化rw時
if($this
$this
if($this
if($this
@mysql_query("SET character_set_connection=$this
}
if($this
@mysql_query("SET sql_mode=
}
}
if($dbname) {
$this
}
}
//連接一個只讀的mysql數據庫
function connect_ro($dbhost
if($this
$this
$this
//不產生halt錯誤
$this
if($this
//連接成功
//echo "link ro sussess!<br>";
$this
$this
if($this
//如果已經選擇過數據庫則需要操作一次
@mysql_select_db($this
}
}else{
//連接失敗
//echo "link ro failed!<br>";
$this
}
}
//設置一系列只讀數據庫並且連接其中一個
function set_ro_list($ro_list){
if(is_array($ro_list)){
//隨機選擇其中一個
$link_ro = $ro_list[array_rand($ro_list)];
$this
}
}
function select_db($dbname) {
//同時操作兩個數據庫連接
$this
if($this
@mysql_select_db($dbname
}
return @mysql_select_db($dbname
}
function fetch_array($query
return mysql_fetch_array($query
}
function fetch_one_array($sql
$qr = $this
return $this
}
function query($sql
$this
//判斷是否select語句
if($this
$this
}
$func = $type ==
if(!($query = $func($sql
$this
}
$this
return $query;
}
function affected_rows() {
return mysql_affected_rows($this
}
function error() {
return (($this
}
function errno() {
return intval(($this
}
function result($query
$query = @mysql_result($query
return $query;
}
function num_rows($query) {
$query = mysql_num_rows($query);
return $query;
}
function num_fields($query) {
return mysql_num_fields($query);
}
function free_result($query) {
return mysql_free_result($query);
}
function insert_id() {
return ($id = mysql_insert_id($this
}
function fetch_row($query) {
$query = mysql_fetch_row($query);
return $query;
}
function fetch_fields($query) {
return mysql_fetch_field($query);
}
function version() {
return mysql_get_server_info($this
}
function close() {
return mysql_close($this
}
function halt($message =
$dberror = $this
$dberrno = $this
echo "<div style="position:absolute;font
<b>MySQL Error</b><br>
<b>Message</b>: $message<br>
<b>SQL</b>: $sql<br>
<b>Error</b>: $dberror<br>
<b>Errno
</div>";
exit();
}
}
?>
From:http://tw.wingwit.com/Article/program/PHP/201311/21039.html