DDR爱好者之家 Design By 杰米
本文实例讲述了php实现带读写分离功能的MySQL类。分享给大家供大家参考,具体如下:
概述:
1. 根据sql语句判断是连接读库还是写库
2. 链式调用$this->where()->get()
3. 不同的主机对应不同的实例, 不再多次new
具体代码如下:
<"`{$this->_database}`.`{$this->_tablename}`"; $this->isRelease = $isRelease; } public static function getInstance($database='', $tablename='', $isRelease=0) { if (self::$Instance == null) { self::$Instance = new DBRWmysql($database, $tablename, $isRelease); } self::$Instance->_database = $database; self::$Instance->_tablename = $tablename; self::$Instance->_dt = "`{$database}`.`{$tablename}`"; self::$Instance->isRelease = $isRelease; return self::$Instance; } //如果主机没变,并且已经存在MYSQL连接,就不再创建新的连接 //如果主机改变,就再生成一个实例创建一个连接 //type == 'write'或'read' public function getLink($type) { $this->dbType = $$type; //随机选取一个数据库连接(区分读写) $dbConfig = DBConfig::$$type; $randKey = array_rand($dbConfig); $config = $dbConfig[$randKey]; //链接数据库 $host = $config['host']; $username = $config['username']; $password = $config['password']; if (empty($this->links[$host])) { $this->_host = $host; $this->links[$host] = new mysqli($host, $username, $password); if($this->links[$host]->connect_error) { $this->error($this->links[$host]->connect_error); } } //初始化链接 $this->link = $this->links[$host]; $this->link->query("set names utf8mb4;"); //支持emoji表情 $this->link->query("use {$this->_database};"); } public function getCurrentLinks() { return $this->links; } //析构函数 public function __destruct() { foreach ($this->links as $v) { $v->close(); } } //查询封装 public function query($sql) { $this->sql = $sql; if (strpos($sql, 'select') !== false) { $this->getLink('read');//读库 } else { $this->getLink('write');//写库 } $this->rs = $this->link->query($sql); ($this->rs === false) && $this->error('sql error: '.$sql.PHP_EOL.$this->link->error); //查询完成后释放链接, 并删除链接对象 if ($this->isRelease) { $this->link->close(); unset($this->links[$this->_host]); } return $this->rs; } //增 public function insert($arrData) { foreach ($arrData as $key=>$value) { $fields[] = $key; $values[] = "'".$value."'"; // $fields[] = '`'.$key.'`'; // $values[] = "'".$value."'"; } $strFields = implode(',', $fields); $strValues = implode(',', $values); $sql = "insert into {$this->_dt} ($strFields) values ($strValues)"; $this->query($sql); $insert_id = $this->link->insert_id; return $insert_id; } //增 public function replace($arrData) { foreach ($arrData as $key=>$value) { $fields[] = $key; $values[] = "'{$value}'"; } $strFields = implode(',', $fields); $strValues = implode(',', $values); $sql = "replace into {$this->_dt} ($strFields) values ($strValues)"; $this->query($sql); return $this->link->insert_id; } //增 //每次插入多条记录 //每条记录的字段相同,但是值不一样 public function insertm($arrFields, $arrData) { foreach ($arrFields as $v) { // $fields[] = "`{$v}`"; $fields[] = $v; } foreach ($arrData as $v) { $data[] = '('.implode(',', $v).')'; } $strFields = implode(',', $fields); $strData = implode(',', $data); $sql = "insert into {$this->_dt} ($strFields) values {$strData}"; $this->query($sql); return $this->link->insert_id; } //删 public function delete() { $where = $this->getWhere(); $limit = $this->getLimit(); $sql = " delete from {$this->_dt} {$where} {$limit}"; $this->query($sql); return $this->link->affected_rows; } //改 public function update($data) { $where = $this->getWhere(); $arrSql = array(); foreach ($data as $key=>$value) { $arrSql[] = "{$key}='{$value}'"; } $strSql = implode(',', $arrSql); $sql = "update {$this->_dt} set {$strSql} {$where} {$this->limit}"; $this->query($sql); return $this->link->affected_rows; } //获取总数 public function getCount() { $where = $this->getWhere(); $sql = " select count(1) as n from {$this->_dt} {$where} "; $resault = $this->query($sql); ($resault===false) && $this->error('getCount error: '.$sql); $arrRs = $this->rsToArray($resault); $num = array_shift($arrRs); return $num['n']; } //将结果集转换成数组返回 //如果field不为空,则返回的数组以$field为键重新索引 public function rsToArray($field = '') { $arrRs = $this->rs->fetch_all(MYSQLI_ASSOC); //该函数只能用于php的mysqlnd驱动 $this->rs->free();//释放结果集 if ($field) { $arrResult = []; foreach ($arrRs as $v) { $arrResult[$v[$field]] = $v; } return $arrResult; } return $arrRs; } //给字段名加上反引号 public function qw($strFields) { $strFields = preg_replace('#\s+#', ' ', $strFields); $arrNewFields = explode(' ', $strFields ); $arrNewFields = array_filter($arrNewFields); foreach ($arrNewFields as $k => $v) { $arrNewFields[$k]= '`'.$v.'`'; } return implode(',', $arrNewFields); } //处理入库数据,将字符串格式的数据转换为...格式(未实现) public function getInsertData($strData) { // $bmap = "jingdu,$jingdu weidu,$weidu content,$content"; } //select in //arrData 整数数组,最好是整数 public function select_in($key, $arrData, $fields='') { $fields = $fields "(select $fields from {$this->_dt} where $key between $s and $e)"; } else { $s = $v[0]; $sql = "(select $fields from {$this->_dt} where $key = $s)"; } $arrSql[] = $sql; } $strUnion = implode(' UNION ALL ', $arrSql); $res = $this->query($strUnion); return $this->rstoarray($res); } //where in public function setWhereIn($key, $arrData) { if (empty($arrData)) { $str = "(`{$key}` in ('0'))"; $this->addWhere($str); return $str; } foreach ($arrData as &$v) { $v = "'{$v}'"; } $str = implode(',', $arrData); $str = "(`{$key}` in ( {$str} ))"; $this->addWhere($str); return $this; } //where in public function setWhere($arrData) { if (empty($arrData)) { return ''; } foreach ($arrData as $k => $v) { $str = "(`{$k}` = '{$v}')"; $this->addWhere($str); } return $this; } //between and public function setWhereBetween($key, $min, $max) { $str = "(`{$key}` between '{$min}' and '{$max}')"; $this->addWhere($str); return $this; } //where a>b public function setWhereBT($key, $value) { $str = "(`{$key}` > '{$value}')"; $this->addWhere($str); return $this; } //where a<b public function setWhereLT($key, $value) { $str = "(`{$key}` < '{$value}')"; $this->addWhere($str); return $this; } //组装where条件 public function addWhere($where) { $this->arrWhere[] = $where; } //获取最终查询用的where条件 public function getWhere() { if (empty($this->arrWhere)) { return 'where 1'; } else { return 'where '.implode(' and ', $this->arrWhere); } } //以逗号隔开 public function setFields($fields) { $this->fields = $fields; return $this; } // order by a desc public function setOrder($order) { $this->arrOrder[] = $order; return $this; } //获取order语句 public function getOrder() { if (empty($this->arrOrder)) { return ''; } else { $str = implode(',', $this->arrOrder); $this->order = "order by {$str}"; } return $this->order; } //e.g. '0, 10' //用limit的时候可以加where条件优化:select ... where id > 1234 limit 0, 10 public function setLimit($limit) { $this->limit = 'limit '.$limit; return $this; } //直接查询sql语句, 返回数组格式 public function arrQuery($sql, $field='') { $this->query($sql); $this->clearQuery(); ($this->rs===false) && $this->error('select error: '.$sql); return $this->rsToArray($field); } //如果 $field 不为空, 则返回的结果以该字段的值为索引 //暂不支持join public function get($field='') { $where = $this->getWhere(); $order = $this->getOrder(); $sql = " select {$this->fields} from {$this->_dt} {$where} {$order} {$this->limit} "; return $this->arrQuery($sql, $field); } //获取一条记录 public function getOne() { $this->setLimit(1); $rs = $this->get(); return !empty($rs) "_blank" href="https://www.jb51.net/Special/768.htm">php+mysqli数据库程序设计技巧总结》、《PHP基于pdo操作数据库技巧总结》、《PHP运算与运算符用法总结》、《PHP网络编程技巧总结》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》希望本文所述对大家PHP程序设计有所帮助。
DDR爱好者之家 Design By 杰米
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
DDR爱好者之家 Design By 杰米
暂无评论...
P70系列延期,华为新旗舰将在下月发布
3月20日消息,近期博主@数码闲聊站 透露,原定三月份发布的华为新旗舰P70系列延期发布,预计4月份上市。
而博主@定焦数码 爆料,华为的P70系列在定位上已经超过了Mate60,成为了重要的旗舰系列之一。它肩负着重返影像领域顶尖的使命。那么这次P70会带来哪些令人惊艳的创新呢?
根据目前爆料的消息来看,华为P70系列将推出三个版本,其中P70和P70 Pro采用了三角形的摄像头模组设计,而P70 Art则采用了与上一代P60 Art相似的不规则形状设计。这样的外观是否好看见仁见智,但辨识度绝对拉满。
更新日志
2024年11月28日
2024年11月28日
- 凤飞飞《我们的主题曲》飞跃制作[正版原抓WAV+CUE]
- 刘嘉亮《亮情歌2》[WAV+CUE][1G]
- 红馆40·谭咏麟《歌者恋歌浓情30年演唱会》3CD[低速原抓WAV+CUE][1.8G]
- 刘纬武《睡眠宝宝竖琴童谣 吉卜力工作室 白噪音安抚》[320K/MP3][193.25MB]
- 【轻音乐】曼托凡尼乐团《精选辑》2CD.1998[FLAC+CUE整轨]
- 邝美云《心中有爱》1989年香港DMIJP版1MTO东芝首版[WAV+CUE]
- 群星《情叹-发烧女声DSD》天籁女声发烧碟[WAV+CUE]
- 刘纬武《睡眠宝宝竖琴童谣 吉卜力工作室 白噪音安抚》[FLAC/分轨][748.03MB]
- 理想混蛋《Origin Sessions》[320K/MP3][37.47MB]
- 公馆青少年《我其实一点都不酷》[320K/MP3][78.78MB]
- 群星《情叹-发烧男声DSD》最值得珍藏的完美男声[WAV+CUE]
- 群星《国韵飘香·贵妃醉酒HQCD黑胶王》2CD[WAV]
- 卫兰《DAUGHTER》【低速原抓WAV+CUE】
- 公馆青少年《我其实一点都不酷》[FLAC/分轨][398.22MB]
- ZWEI《迟暮的花 (Explicit)》[320K/MP3][57.16MB]