There are three common ways of doing this,
1, automatically determine whether SQL is read, to select the database connection:
When instantiating a PHP db class, you need to connect two servers at a time, and then choose different connections based on SLQ, for example:
- $link _w = mysql_connect ($w _host, $user, $pwd);
- $link _r = mysql_connect ($r _host, $user, $pwd);
- Execute SQL
- if (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 executes SQL without distinguishing between reading and writing, and at the bottom of the DB class, the disadvantage is that it is often necessary to open two connections only when reading or writing.
2, call the time you choose:
It is generally possible to determine whether to write or read before executing SQL, so developers need to call different connections manually, for example:
$w _db = new db (' W ');
$w _db, query (' INSERT INTO ... ');
When SQL is read:
$r _db = new db (' R ');
$r _db, query (' Select ... ');
Mainly through, pass parameters to distinguish whether SQL is read or write, each call to SQL needs to call the developer's own judgment.
3, using Mysqlproxy to do the middle-tier proxy, will automatically determine the SQL is read or write, the request forwarded to the server. The advantage is that the program does not have to change any code, as long as the MySQL proxy is started by specifying a read or write server:
--proxy-backend-addresses
--proxy-read-only-backend-addresses
How PHP accesses a DB cluster