How to achieve separation of reading and writing in PHP

王林
Release: 2023-02-26 19:20:01
Original
2997 people have browsed it

How to achieve separation of reading and writing in PHP

There are several ways to separate reading and writing in MySQL

1. MySQL middleware

2. MySQL Driver layer

3. Code control

I won’t go into details about the middleware and driver layer here. Let’s briefly introduce how to control it through PHP code. MySQL reads and writes separated.

We all know that "reading" in the SQL statement is "SELECT" and "writing" is "INSERT", so the first thing we should think of is the string interception substr() function.

First we use the substr() function to get whether the first 6 characters of the sql statement are "SELECT". If so, we connect to the read server for processing. If not, we connect to the write server for processing.

Example code:

$querystr = strtolower(trim(substr($sql,0,6)));    //截取SQL语句字符串

//如果是select,就连接slave(从)服务器
if($querystr == 'select')
{
  $slave_server='192.168.80.3::3306';
  $dsn="mysql:host=$slave_server;dbname=3d";
  $user='root';
  $pass='root';
  $dbh=new PDO($dsn, $user, $pass);
  $res=$dbh->query($sql)->fetchAll(PDO::FETCH_ASSOC);
}
//如果不是select,就连接master(主)服务器
else
{
  $master_server='192.168.33.22::3306';
  $dsn="mysql:host=$master_server;dbname=3dprintsys";
  $user='root';
  $pass='123456';
  $dbh=new PDO($dsn, $user, $pass);
  $res=$dbh->exec($sql);
}
Copy after login

Recommended tutorial: PHP video tutorial

The above is the detailed content of How to achieve separation of reading and writing in PHP. For more information, please follow other related articles on the PHP Chinese website!

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!