


Mysqldb read-write separation operation class implemented by PHP
This article mainly introduces the mysqldb read-write separation operation class implemented by PHP. It analyzes PHP's read-write separation operation implementation skills for the database in the form of examples, and gives the specific usage of this encapsulation class. Friends who need it You can refer to the following
The example of this article describes the mysqldb read-write separation operation class implemented by PHP. Share it with everyone for your reference, the details are as follows:
/** * php MysqlDB 读写分离类 * ----------------------------------------------------- * $Source: http://code.ilaopo.net/php.class.mysqldb $ * $Author: Bevin Chen $ * $Email: bevin#lifa8.cn $ * $Date: 2009-10-10 $ * ----------------------------------------------------- */ class mysqldb { var $querynum = 0; var $linkr,$linkw,$charset,$pconnect,$dbconfig; function __constructor($dbarray) { $this->mysqldb($dbarray); } function mysqldb($dbarray,$dbcharset='utf8',$pcontent=0) { if(!is_array($dbarray[0])) { echo "数据库参数错误"; return false; } $this->charset = $dbcharset; $this->pconnect = $pconnect; $this->dbconfig['master'] = $dbarray[0]; $dbServerNum = count($dbarray); if($dbServerNum > 1) { /* * 当x=1 时,$dbarray[0]不作slave * 当x=0 时,$dbarray[0]作slave */ $x = 1; $rand = rand($x,$dbServerNum-1); $this->dbconfig['slave'] = $dbarray[$rand]; } else { $this->dbconfig['slave'] = false; } } function connect($dbhost,$dbuser,$dbpw,$dbname) { if($this->pconnect) { $link = @mysql_pconnect($dbhost, $dbuser, $dbpw); } else { $link = @mysql_connect($dbhost, $dbuser, $dbpw, 1); } if($link) { if($this->version($link) > '4.1') { if($this->charset) { @mysql_query("SET character_set_connection=".$this->charset.", character_set_results=".$this->charset.", character_set_client=binary", $link); } if($this->version($link) > '5.0.1') { @mysql_query("SET sql_mode=''", $link); } } if($dbname) { @mysql_select_db($dbname, $link); } //print_r($link); return $link; } else { return false; } } function connectM() { if(!$this->linkw = $this->connect($this->dbconfig['master'][0],$this->dbconfig['master'][1],$this->dbconfig['master'][2],$this->dbconfig['master'][3])) { exit("主数据库连接失败!"); } //echo "<br>##connectM!.<br>"; } function connectS() { if($this->dbconfig['slave']) { if(!$this->linkr = $this->connect($this->dbconfig['slave'][0],$this->dbconfig['slave'][1],$this->dbconfig['slave'][2],$this->dbconfig['slave'][3])) { $this->dbconfig['slave'] = false; $this->connectS(); } //echo "<br>##connectS!.<br>"; } else { if(!$this->linkw) { $this->connectM(); } $this->linkr = $this->linkw; } } // db read function query($sql, $type = '') { if(!$this->linkr) { $this->connectS(); } $func = $type == 'UNBUFFERED' && @function_exists('mysql_unbuffered_query') ? 'mysql_unbuffered_query' : 'mysql_query'; $query = $func($sql, $this->linkr); $this->querynum++; return $query; } function fetch_array($query, $result_type = MYSQL_ASSOC) { return @mysql_fetch_array($query, $result_type); } function fetch_row($query) { $query = mysql_fetch_row($query); return $query; } function fetch_One($sql) { $query = $this->query($sql); return $this->fetch_row($query); } /* 获取分页方法 */ function fetch_page($sql, $pagenum) { $page = intval($_GET['page']); $query = $this->query($sql); $countnum = $this->num_rows($query); $countpage = ceil($countnum/$pagenum); if($page<1) { $page=1; } if($page>$countpage) { $page=$countpage; } $limitstart = ($page-1)*$pagenum; /* 获取数据结果集 */ for ($i=0; $i<($limitstart+$pagenum); $i++) { if($i>=$countnum) { break; } if($i>=$limitstart) { $result[] = $this->fetch_array($query); } else { $this->fetch_array($query); } } /* 生成url */ $url = $_SERVER['QUERY_STRING']; $url = preg_replace("/&?page=[0-9]+/i","",$url); $array['countnum'] = $countnum; $array['countpage'] = $countpage; $array['result'] = $result; $array['page'] = $page; if($page>1) { $array['preurl'] = "?".$url."&page=".($page-1); $array['prepage'] = $page-1; } else { $array['preurl'] = "?".$url."&page=1"; $array['prepage'] = 1; } if($page<$countpage) { $array['nexturl'] = "?".$url."&page=".($page+1); $array['nextpage'] = $page+1; } else { $array['nexturl'] = "?".$url."&page=".$countpage; $array['nextpage'] = $countpage; } $array['firsturl'] = "?".$url."&page=1"; $array['firstpage'] = 1; $array['lasturl'] = "?".$url."&page=".$countpage; $array['lastpage'] = $countpage; $array['nopage'] = "?".$url."&page="; return $array; } // db write function queryw($sql, $type = '') { if(!$this->linkw) { $this->connectM(); } $func = $type == 'UNBUFFERED' && @function_exists('mysql_unbuffered_query') ? 'mysql_unbuffered_query' : 'mysql_query'; $query = $func($sql, $this->linkw); $this->querynum++; return $query; } function update($table,$where,$array) { $whereset = $set = $dot = ''; foreach($array as $key=>$value) { $set .= $dot." `$key`='$value'"; $dot = ','; } $whereset = $dot = ''; foreach($where as $k=>$v) { $whereset .= $dot." `$k`='$v'"; $dot = ' and '; } $sql = "update $table set $set where $whereset"; return $this->queryw($sql); } function insert($table,$array) { $col = $v = $dot = ''; foreach($array as $key=>$value) { $v .= $dot."'$value'"; $col .= $dot."`$key`"; $dot = ','; } $sql = "insert into $table ($col) values ($v)"; if($this->queryw($sql)) { return $this->insert_id(); } else { return false; } } function insert_id() { return ($id = mysql_insert_id($this->linkw)) >= 0 ? $id : $this->result($this->queryw("SELECT last_insert_id()"), 0); } // db other function affected_rows($link) { return mysql_affected_rows($link); } function error($link) { return (($link) ? mysql_error($link) : mysql_error()); } function errno($link) { return intval(($link) ? mysql_errno($link) : mysql_errno()); } function result($query, $row) { $query = @mysql_result($query, $row); return $query; } function num_rows($query) { $query = mysql_num_rows($query); return $query; } function num_fields($query) { return mysql_num_fields($query); } function free_result($query) { return mysql_free_result($query); } function fetch_fields($query) { return mysql_fetch_field($query); } function version($link) { return mysql_get_server_info($link); } function close($link) { return mysql_close($link); } } /* 测试例子 // * $dbarray[] = array('localhost','bevin','password','test'); * $dbarray[] = array('ilaopo.net','root','password','test'); * $dbarray[] = array('192.168.1.77','cxh','password','test'); * $newdb = new mysqldb($dbarray,'utf8'); * $array = array('name' => date("Y-m-d H:i:s")); * $id = $newdb->insert("test",$array); * $result = $newdb->fetch_page("select * from test order by id desc",'10'); * print_r($result); * $id = $newdb->insert("test",$array); * echo $id; */
The above is the entire content of this article, I hope it will be helpful to everyone's study.
Related recommendations:
Python implements encapsulation of MySQLdb basic operation classes
##python How to install the mysqldb module under windows
Installing the MySQLdb module under Python environment
The above is the detailed content of Mysqldb read-write separation operation class implemented by PHP. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
