: This article mainly introduces the methods for accessing database clusters in PHP. For more information about PHP tutorials, see. This article summarizes and analyzes the PHP method for accessing the database cluster. We will share this with you for your reference. The details are as follows:
There are three common practices:
1. automatically determine whether the SQL is read to select the database connection:
When instantiating the php DB class, you need to connect two servers at a time and select different connections based on slq. for example:
$ Link_w = mysql_connect ($ w_host, $ user, $ pwd); $ link_r = mysql_connect ($ r_host, $ user, $ pwd ); // execute sqlif (preg_match ("/^ select/I", trim ($ SQL) {mysql_query ($ SQL, $ link_r);} else {mysql_query ($ SQL, $ link_w );}
The advantage of this method is that the developer does not need to differentiate between read and write for executing SQL statements. at the bottom layer of the db class, the developer determines whether to enable two connections only when reading or writing data.
2. choose the following when calling:
Before executing the SQL statement, you can determine whether to write or read the SQL statement. Therefore, developers need to manually call different connections. for example:
$ W_db = new DB ('w'); $ w_db-> query ('Insert .....');
When SQL is read:
$ R_db = new DB ('r'); $ r_db-> query ('select .....');
It mainly uses the passed parameters to distinguish whether the SQL is read or write. before each SQL call, you need to call the developer to determine whether the SQL is read or write.
3. when MySQL Proxy is used as the middle layer Proxy, the system automatically reads or writes the SQL statement and forwards the request to the server. The advantage is that the program does not need to change any code, as long as you specify the read or write server when starting the mysql proxy:
-- Proxy-backend-addresses -- proxy-read-only-backend-addresses