How PHP accesses a DB cluster

Source: Internet
Author: User

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:

    1. $link _w = mysql_connect ($w _host, $user, $pwd);
    2. $link _r = mysql_connect ($r _host, $user, $pwd);
    3. Execute SQL
    4. if (Preg_match ("/^select/i", Trim ($sql))) {
    5. mysql_query ($sql, $link _r);
    6. }else {
    7. mysql_query ($sql, $link _w);
    8. }

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.