PHP操作Mysql数据库读写分离的例子
php实现mysql数据库的读写分离。
假设有两台数据库服务器:
127.0.0.1:3306 为读的数据库
127.0.0.2:3306 为写的数据库
代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
<? /** * mysql读写分离 * by http://www.phperblog.cn */ class db { public function __construct($sql) { $chestr = strtolower(trim($sql)); //判断sql语句有select关键字的话,就连接读的数据库,否则就连接写数据库 if(substr($chestr,0,6)=='select') { echo 'I am using select db..<br>'; $link = mysql_connect("127.0.0.1:3306", "root", "") or die("Could not connect: " . mysql_error()); mysql_select_db("test"); $result = mysql_query($sql); while ($row = mysql_fetch_array($result, MYSQL_NUM)) { printf("%s %s", $row[0],$row[1]); } echo mysql_get_host_info($link).mysql_get_server_info($link).mysql_get_proto_info($link).mysql_get_client_info().'<br>'; } else { echo 'I am using insert db..<br>'; $link = mysql_connect("127.0.0.2:3306","root","") or die("Could not connect: " . mysql_error()); mysql_select_db("test"); $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().'<br>'; } } } $d = new db("update `users` set `select`='fasdf' where `id` =1"); $d2 = new db("SELECT * from `users`"); |
- java学习知识积累-spring框架接收url参数并输出
- ThinkPHP实现MySQL读写分离