?php
/**
* mysql读写分离
*/
class db{
public function __construct($sql){
$chestr = strtolower(trim($sql));
//判断sql语句有select关键字的话,就连接读的数据库,否则就连接写数据库
if(substr($chestr,0,6)=='select')
{
echo 'I am using slave db..br>';
$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().'br>';
}else{
echo 'I am using master db..br>';
$link = mysql_connect("192.168.20.195:3306","open","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().'br>';
}
}
}
$master = new db("INSERT INTO user (id,name)VALUES (NULL,'100')");
$slave = new db("SELECT * from `user`");
更多关于PHP相关内容感兴趣的读者可查看本站专题:《php+mysql数据库操作入门教程》、《php+mysqli数据库程序设计技巧总结》、《php面向对象程序设计入门教程》、《PHP数组(Array)操作技巧大全》、《php字符串(string)用法总结》及《php常见数据库操作技巧汇总》