This article mainly introduces the PHP implementation of the MySQL read and write separation operation, a simple description of the MySQL read and write separation principle, and in combination with the example of PHP for MySQL read and write SQL statement operation of different database related implementation skills, the need for friends can refer to the next
This paper describes the MySQL read-write separation operation implemented by PHP. Share to everyone for your reference, as follows:
First MySQL master and slave needs to be configured, the basic principle is to determine whether the SQL statement is a SELECT, then go to Master Library, otherwise from slave
<?php/*** MySQL read-write separation */class db{public Function __construct ($sql) {$chestr = Strtolower (Trim ($sql)); To determine if the SQL statement has the SELECT keyword, connect to the read database, otherwise connect the write database if (substr ($chestr, 0,6) = = ' select ') {echo ' I am using slave db. <br> '; $link = mysql_connect ("192.168.20.201:3306", "open", "123456") or Die ("Could Not connect:". Mysql_error ()); mysql_select_db ("Hadoop"); $result = mysql_query ($sql); while ($row = Mysql_fetch_array ($result, Mysql_assoc)) {$data []= $row; }//print_r ($data); exit; echo Mysql_get_host_info ($link). Mysql_get_server_info ($link). Mysql_get_proto_info ($link). Mysql_get_client_info ( ).' <br> '; }else{Echo ' I am using Master db. <br> '; $link = mysql_connect ("192.168.20.195:3306", "open", "123456") or Die ("Could Not connect:". Mysql_error ()); mysql_select_db ("Hadoop"); $result = mysql_query ($sql); echo @mysql_affected_rows ($result); echo Mysql_get_host_info ($link). mysql_get_server_inFo ($link). Mysql_get_proto_info ($link). Mysql_get_client_info (). ' <br> '; }}} $master = new db ("INSERT into User (Id,name) VALUES (NULL, ')"), $slave = new db ("SELECT * from ' user ');
Results:
I am using Master db.
192.168.20.195 via Tcp/ip5.1.73-log10mysqlnd 5.0.8-dev-20102224-$Id: 731e5b87ba42146a687c29995d2dfd8b4e40b325 $
I am using slave db.
192.168.20.201 via Tcp/ip5.1.73-log10mysqlnd 5.0.8-dev-20102224-$Id: 731e5b87ba42146a687c29995d2dfd8b4e40b325 $
Articles you may be interested in:
PHP implementation to compress multiple files into a zip format and download to the local method
PHP Recursive Traversal folder to remove comments and compress PHP source code sample method
Example of a simple implementation method for the PHP factory pattern