本文实例讲述了PHP实现的MysqL读写分离操作。分享给大家供大家参考,具体如下:
首先MysqL主从需配置好,基本原理就是判断sql语句是否是select,是的话走master库,否则从slave查
PHP;">
PHP
/**
* MysqL读写分离
*/
class db{
public function __construct($sql){
$chestr = strtolower(trim($sql));
//判断sql语句有select关键字的话,就连接读的数据库,否则就连接写数据库
if(substr($chestr,6)=='select')
{
echo 'I am using slave db..
'; $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().'
'; }else{ echo 'I am using master db..
'; $link = MysqL_connect("192.168.20.195:3306","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().'
'; } } } $master = new db("INSERT INTO user (id,name)VALUES (NULL,'100')"); $slave = new db("SELECT * from `user`");
'; $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().'
'; }else{ echo 'I am using master db..
'; $link = MysqL_connect("192.168.20.195:3306","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().'
'; } } } $master = new db("INSERT INTO user (id,name)VALUES (NULL,'100')"); $slave = new db("SELECT * from `user`");
结果:
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 $
更多关于PHP相关内容感兴趣的读者可查看本站专题:《》、《》、《》、《》、《》及《》
希望本文所述对大家PHP程序设计有所帮助。
原文链接:https://www.f2er.com/php/16030.html