MySQL class implemented by PHP that supports reading and writing separation

WBOY
Release: 2016-07-25 08:56:07
Original
900 people have browsed it
  1. /**

  2. * MySQL read-write separation class
  3. * $db_config = array(
  4. * 'master' => array('host'=>'localhost:3306','user'=>'admin','passwd'= >'123456','db'=>'stat'),
  5. * 'slave' => array(
  6. * array('host'=>'localhost:3307','user'=>' admin','passwd'=>'123456','db'=>'stat'),
  7. * array('host'=>'localhost:3308','user'=>'admin', 'passwd'=>'123456','db'=>'stat')
  8. * )
  9. * );
  10. *
  11. * Note: If there are multiple slaves, randomly connect one of them
  12. * Last edit: bbs .it-home.org
  13. */
  14. /*
  15. $db_config = array(
  16. 'master' => array('host'=>'localhost:3306','user'=>'admin','passwd'=>'123456','db'=>'stat'),
  17. 'slave' => array(
  18. array('host'=>'localhost:3307','user'=>'admin','passwd'=>'123456','db'=>'stat'),
  19. array('host'=>'localhost:3308','user'=>'admin','passwd'=>'123456','db'=>'stat')
  20. )
  21. );

  22. $db = MySQL::getInstance('','r-w');

  23. $sql = "select * from admin";

  24. $rs = $db->query($sql);

  25. while ($row = $db->fetch($rs)){
  26. echo "uid:".$row['uid']." ".$row['userName']."
    ";
  27. }

  28. echo "


    ";
  29. */

  30. class MySQL

  31. {
  32. private static $_instance = null;//数据库连接实例
  33. private static $_master = null;//主数据库连接实例
  34. private static $_slave = null;//重数据库连接实例
  35. public $_config = array();//数据库连接配置信息
  36. public $_res = null;//查询实例句柄
  37. public $_flag = '';//标识当前语句是在主还是重数据库上执行
  38. public $_link = null;
  39. /**
  40. * Single instance
  41. * Enter description here ...
  42. * @param unknown_type $dbname
  43. * @param unknown_type $mode
  44. */
  45. public static function & getInstance($dbname='',$mode='rw'){
  46. if (is_null(self::$_instance)){
  47. self::$_instance = new self();
  48. self::$_instance->__getConf();
  49. self::$_instance->connect($dbname,$mode);
  50. }
  51. return self::$_instance;
  52. }

  53. /**

  54. * Get database configuration information
  55. * Enter description here...
  56. */
  57. public function __getConf(){
  58. global $db_config;
  59. $this->_config['master'] = $db_config['master'];
  60. $this->_config['slave'] = $db_config['slave'];
  61. }
  62. /**
  63. * Database connection
  64. * Enter description here...
  65. * @param $dbname specifies the database name to connect to. By default, the library of the configuration file is connected
  66. * @param $mode rw means connecting to the main library, r-w means reading and writing separation
  67. */
  68. public function connect($dbname='',$mode = 'rw'){
  69. if($mode == 'rw'){
  70. if(is_null(self::$_master)){
  71. $this->_master = $this->_slave = $this->conn_master($dbname);
  72. }
  73. }else{
  74. if(is_null(self::$_master)){
  75. $this->_master = $this->conn_master($dbname);
  76. }
  77. if(is_null(self::$_slave)){
  78. $this->_slave = $this->conn_slave($dbname);
  79. }
  80. }
  81. }
  82. /**
  83. * Connect to the main database server
  84. * Enter description here...
  85. */
  86. public function conn_master($dbname=''){
  87. $_link = mysql_connect($this->_config['master']['host'],$this->_config['master']['user'],$this->_config['master']['passwd'],true) or die ("Connect ".$this->_config['master']['host']." fail.");
  88. mysql_select_db(empty($dbname)?$this->_config['master']['db']:$dbname,$_link) or die(" The DB name ".$this->_config['master']['db']." is not exists.");
  89. mysql_query("set names utf8",$_link);
  90. return $_link;
  91. }
  92. /**
  93. * Connect to slave database server
  94. * Enter description here...
  95. */
  96. public function conn_slave($dbname=''){
  97. $offset = rand(0,count($this->_config['slave'])-1);
  98. $_link = @mysql_connect($this->_config['slave'][$offset]['host'],$this->_config['slave'][$offset]['user'],$this->_config['slave'][$offset]['passwd'],true) or die(" Connect ".$this->_config['slave'][$offset]['host']." fail.");
  99. mysql_select_db(empty($dbname)?$this->_config['slave'][$offset]['db']:$dbname,$_link) or die(" The DB name ".$this->_config['slave'][$offset]['db']." is not exists.");
  100. mysql_query("set names utf8",$_link);
  101. return $_link;
  102. }

  103. /**

  104. * Execute database query
  105. * Enter description here ...
  106. * @param string $sql
  107. */
  108. public function query($sql,$master=true){

  109. if($master == true || (substr(strtolower($sql),0,6) != 'select') && $master == false){

  110. $this->_res = mysql_query($sql,$this->_master);
  111. if(!$this->_res){
  112. $this->_error[] = mysql_error($this->_master);
  113. }
  114. $this->_flag = 'master';
  115. $this->_link = $this->_master;
  116. } else {
  117. $this->_res = mysql_query($sql,$this->_slave);
  118. if(!$this->_res){
  119. $this->_error[] = mysql_error($this->_slave);
  120. }
  121. $this->_flag = 'slave';
  122. $this->_link = $this->_slave;
  123. }

  124. return $this->_res;

  125. }
  126. /**
  127. * Get a single row of records
  128. * Enter description here ...
  129. * @param mixed $rs
  130. */
  131. public function get($rs=''){
  132. if(empty($rs)){
  133. $rs = $this->_res;
  134. }
  135. return mysql_fetch_row($rs);
  136. }
  137. /**
  138. * Get multi-line records
  139. * Enter description here ...
  140. * @param mixed $rs
  141. * @param $result_type
  142. */
  143. public function fetch($rs = ''){
  144. if(empty($rs)){
  145. $rs = $this->_res;
  146. }
  147. return mysql_fetch_array($rs,MYSQL_ASSOC);
  148. }
  149. /**
  150. * Insert data
  151. * Enter description here ...
  152. * @param unknown_type $sql
  153. */
  154. public function add($sql){
  155. $rs = $this->query($sql);
  156. if($rs)
  157. return mysql_insert_id($this->_link);
  158. return false;
  159. }
  160. /**
  161. * Update data
  162. * Enter description here ...
  163. * @param unknown_type $sql
  164. */
  165. public function update($sql){
  166. if(empty($sql)) return false;
  167. $rs = $this->query($sql);
  168. if($rs)
  169. return $this->fetchNum();
  170. return false;
  171. }

  172. /**

  173. * Get the number of rows affected by the previous statement
  174. * Enter description here...
  175. */
  176. public function fetchNum(){
  177. return mysql_affected_rows($this->_link);
  178. }
  179. /**
  180. * Destructor, releases database connection resources
  181. * Enter description here...
  182. */
  183. public function __destruct(){
  184. mysql_close($this->_link);
  185. }
  186. }

复制代码


source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!