Example of mysql read write separation operation implemented by PHP

  • 2021-10-11 17:59:24
  • OfStack

In this paper, an example is given to describe the mysql read-write separation operation realized by PHP. Share it for your reference, as follows:

First of all, mysql master and slave need to be configured well. The basic principle is to judge whether sql statement is select. If yes, go to master library, otherwise, check from slave


<?php
/**
* mysql Separation of reading and writing 
*/
class db{
  public function __construct($sql){
    $chestr = strtolower(trim($sql));
    // Judge sql Statement has select Keyword, connect to the read database , Otherwise, connect to write to the 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,'100')");
$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 $

For more readers interested in PHP related contents, please check the topics on this site: "Introduction to php+mysql Database Operation", "Summary of php+mysqli Database Programming Skills", "Introduction to php Object-Oriented Programming", "Encyclopedia of PHP Array (Array) Operation Skills", "Summary of php String (string) Usage" and "Summary of php Common Database Operation Skills"

I hope this article is helpful to everyone's PHP programming.


Related articles: