Home php教程 PHP源码 php编写的mysql 操作类 php5的

php编写的mysql 操作类 php5的

May 25, 2016 pm 05:10 PM

php编写的mysql 操作类 php5的 

<?php 
/*mysql 简单类 by joffe q89949401 围脖@狂code诗人;
本类全静态 使用的时候直接include后 用mysql::方法()名即可 由于类在php5里面全局可视,所以不必担心变量范围的问题.如果有什么意见 请围脖私信||qq邮件;
目前没有与存储过程有关的方法,当然存储过程一般是创建数据库的时候做的.
config文件需要配置以下常量信息:
LIB:类存放位置
DEBUG:是否开启debug(如果开启会输出错误信息跟踪)
TB_EX:数据库表前缀;
*/
defined(&#39;LIB&#39;) or die(&#39;Missing config!!&#39;);
final class mysql {  
/**  
* 查询总次数  
*  
* @var int  
*/  
public static $querynum = 0;  
/**  
* 连接句柄  
*  
* @var object  
*/  
public static $link;  
/*
表前缀
@var string 下面方法需要在配置文件中配置TB_EX 作为表的前缀
*/

static function add_ex($tb){
	return TB_EX.$tb_ex.$tb;
}
 /*mysql数据库是否使用严格的类型(mysql类型没开启自动转换)默认为false,表示mysql有开启类型转换,这个变量目前只要是用于insert函数的单引号在没有自动转换的mysql里面的问题,可能将来会增加相关函数
 
 */
public static $is_type_tight=false;

/**  
* 构造函数  
*  
* @param string $dbhost 主机名  
* @param string $dbuser 用户  
* @param string $dbpw 密码  
* @param string $dbname 数据库名  
* @param int $pconnect 是否持续连接  
*/  
static function connect($dbhost, $dbuser, $dbpw, $dbname = "",$dbcharset, $pconnect = 0) {  
if($pconnect) {  
if(!self::$link = @mysql_pconnect($dbhost, $dbuser, $dbpw)) {  
self::halt("Can not connect to MySQL server");  
}  
} else {  
if(!self::$link = @mysql_connect($dbhost, $dbuser, $dbpw)) {  
self::halt("Can not connect to MySQL server");  
}  
}  
if(self::version() > "4.1") {   
if($dbcharset) {  
mysql_query("SET character_set_connection={$dbcharset}, character_set_results=$dbcharset, character_set_client=binary", self::$link);  
}  
if(self::version() > "5.0.1") {  
mysql_query("SET sql_mode=&#39;&#39;", self::$link);  
}  
}  
if($dbname) {  
mysql_select_db($dbname, self::$link);  
}  
}  
/**  
* 选择数据库  
*  
* @param string $dbname  
* @return   
*/  
static function select_db($dbname) {  
return mysql_select_db($dbname, self::$link);  
}  
/**  
* 取出结果集中一条记录  
*  
* @param object $query  
* @param int $result_type  
* @return array  
*/  
static function fetch_array($query, $result_type = MYSQL_ASSOC) {  //默认只取关联数组 不取数字数组.
return mysql_fetch_array($query, $result_type);  
}  
 
/**  
* 查询SQL  
*  
* @param string $sql  
* @param string $type  
* @return object  
*/  
static function query($sql, $type = "") {  
 $func = $type == "UNBUFFERED" && @function_exists("mysql_unbuffered_query") ?  
"mysql_unbuffered_query" : "mysql_query";  
if(!($query = $func($sql, self::$link)) && $type != "SILENT") {  
self::halt("MySQL Query Error", $sql);  
}  
self::$querynum++;  
return $query;  
}  
/**  
* 取影响条数  
*  
* @return int  
*/  
static function affected_rows() {  
return mysql_affected_rows(self::$link);  
}  
/**  
* 返回错误信息  
*  
* @return array  
*/  
static function error() {  
return ((self::$link) ? mysql_error(self::$link) : mysql_error());  
}  
/**  
* 返回错误代码  
*  
* @return int  
*/  
static function errno() {  
return intval((self::$link) ? mysql_errno(self::$link) : mysql_errno());  
}  
/**  
* 返回查询结果  
*  
* @param object $query  
* @param string $row  
* @return mixed  
*/  
static function result($query, $row,$flname=0) {  
$query = @mysql_result($query, $row,$flname);  
return $query;  
}  
/**  
* 结果条数  
*  
* @param object $query  
* @return int  
*/  
static function num_rows($query) {  
$query = mysql_num_rows($query);  
return $query;  
}  
/**  
* 取字段总数  
*  
* @param object $query  
* @return int  
*/  
static function num_fields($query) {  
return mysql_num_fields($query);  
}  
/**  
* 释放结果集  
*  
* @param object $query  
* @return bool  
*/  
static function free_result($query) {  
return @mysql_free_result($query);  
}  
/**  
* 返回自增ID  
*  
* @return int  
*/  
static function insert_id() {  
return ($id = mysql_insert_id(self::$link)) >= 0 ? $id : self::$result(self::$query("SELECT last_insert_id()"), 0);  
}  
/**  
* 从结果集中取得一行作为枚举数组  
*  
* @param object $query  
* @return array  
*/  
static function fetch_row($query) {  
$query = mysql_fetch_row($query);  
return $query;  
}  
/**  
* 从结果集中取得列信息并作为对象返回  
*  
* @param object $query  
* @return object  
*/  
static function fetch_fields($query) {  
return mysql_fetch_field($query);  
}  

static function select_affectedt_rows($rs){
	 return mysql_affected_rows($rs,self::$link);
	
}
/**  
* 返回mysql版本  
*  
* @return string  
*/  
static function version() {  
return mysql_get_server_info(self::$link);  
}  
/**  
* 关闭连接  
*  
* @return bool  
*/  
static function close() {  
return mysql_close(self::$link);  
}  
/**  
* 输出错误信息  
*  
* @param string $message  
* @param string $sql  
*/  
static function halt($message = "", $sql = "") {
	 @header("Content-type: text/html; charset=utf-8");
	 
	if (DEBUG==1){
		$debug = debug_backtrace();
		echo $message . "\r\n<br/>SQL--> " . $sql."\r\n<br/>ERROR_MESSAGE-->".self::error().
		"\r\n<br/>--------------debug--------------\r\n<br/>";
		self::echoarray($debug);
		echo "\r\n<br/>-------------debug end----------------";  
		
  	}else{
		echo &#39;SQL Error&#39;;
	}
	@self::rollback();
	exit;
}  
/////////////////////////////以下是扩展的sql方法.//////
/* 把数组按照 key value value 的对应关系插入数据表table中
table 要插入的数据表
要注意 这些扩展方法是没自己给表有加前缀的.
*/
static function insert($table,$array){
	$temp="";$temp2=&#39;&#39;;
	foreach($array as $key=>$value){
		if(self::$is_type_tight){
			if(is_string($value)){
				$temp .="$key,";$temp2 .="&#39;$value&#39;,";
			}elseif(is_int($value||is_null($value)||is_float($value))){
				$value+=0;
				$temp .="$key,";$temp2 .="&#39;$value&#39;,";
			}
		}else{
			$temp .="$key,";$temp2 .="&#39;$value&#39;,";
		}
	}
	$temp = substr($temp,0,strlen($temp)-1);
	$temp2 = substr($temp2,0,strlen($temp2)-1);
	
	$sql = "INSERT INTO $table ($temp) VALUE($temp2)";
	return self::query($sql);
}


static function del($table,$where){
	$sql = "DELETE FROM {$table} where {$where}";
	return self::query($sql);
}

static function update($table,$array,$where){
	foreach ($array as $key=>$value){
		$temp .= "$key=&#39;$value&#39;,";
	}
	$temp = substr($temp,0,strlen($temp)-1);
	$sql = "update {$table} set ($temp) where {$where} ";
	return self::query($sql);
}

/*进行数据库查询select 参数不定
参数说明:所有参数必须是string
第一个参数必须是表名;
从第二个参数起,
如果是写上 "where:XXX" 则认为是where条件;
如果写上 "xxx" 则认为是键值
如果写上 "by:XXX" 则认为是排序
如果写上 "limit:xxx,xxx" 则认为是分页

#参数不正确则返回false; 成功查询返回查询后的数组;
*/
static function select(){
	$numargs = func_num_args();//获取参数个数;
	$where = "";$key="";$limit="";$by="";
	if($numargs==0){return false;}
	//echo $numargs;
	if($numargs>=2){
		$arg_list = func_get_args();
		$table = $arg_list[0];
		unset($arg_list[0]);
	//	print_r($arg_list);
		foreach($arg_list as $k=>$value){
			if(preg_match("#^(where:)\w#",$value)){
				$temp = explode(":",$value);
					$where = "WHERE {$temp[1]} " ;
			}elseif(preg_match("#^by:\w#",$value)){
				$temp = explode(":",$value);
				$by = "order by {$temp[1]}" ;
			}elseif(preg_match("#^limit:\w#",$value)){
				$temp = explode(":",$value);
				$limit = "limit {$temp[1]}";
			}else{
				$key .= "$value,";
			}
		}
		
		if($key==""){
			$key = "*";
		}else{
			$key =substr($key,0,strlen($key)-1); 
		}
		
	$sql_base="SELECT $key FROM $table";
	}
	if(!empty($where)){
		$sql_base .= " $where";
	}
	if(!empty($by)){
		$sql_base .= " $by";
	}
	if(!empty($limit)){
		$sql_base .= " $limit";
	}
	//echo $sql_base;
	//echo $by ;
	$rs = self::query($sql_base);
	$re=array();
	if(self::num_rows($rs)>=1){
		while($info = self::fetch_array($rs)){
			$re[]=$info;
		}
	}
	self::free_result($rs);
	return $re;
	}
	
	
	/*回滚事务*/
	static function rollback(){
		self::query(&#39;rollback&#39;);
	}
	/*开始事务*/
	static function begin(){
		self::query(&#39;SET AUTOCOMMIT =0&#39;); //停用自动提交;
		self::query(&#39;BEGIN&#39;) ;//开始一个事务;
	}
	
	/*提交事务*/
	static function commit(){
		self::query(&#39;commit&#39;);
	}


 	static function echoarray($array){
		foreach($array as $k=>$v ){
			if(is_array($v)){
				if(is_array($v)){
					echo "<br/>--------------------------------<br/>";
					self::echoarray($v);
				}
			}else{
				if($k===&#39;line&#39;)
				echo "<b style=&#39;color:red&#39;>$k -> " .$v."</b>  ";
				else
				echo "$k -> " .$v."  ";
			}
		}
	}

	static function get_server_info(){
		return mysql_get_server_info();
	}
}  

?>
Copy after login

 以上就是php编写的mysql 操作类 php5的 的内容,更多相关内容请关注PHP中文网(www.php.cn)!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Laravel Introduction Example Laravel Introduction Example Apr 18, 2025 pm 12:45 PM

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

Solve database connection problem: a practical case of using minii/db library Solve database connection problem: a practical case of using minii/db library Apr 18, 2025 am 07:09 AM

I encountered a tricky problem when developing a small application: the need to quickly integrate a lightweight database operation library. After trying multiple libraries, I found that they either have too much functionality or are not very compatible. Eventually, I found minii/db, a simplified version based on Yii2 that solved my problem perfectly.

Laravel framework installation method Laravel framework installation method Apr 18, 2025 pm 12:54 PM

Article summary: This article provides detailed step-by-step instructions to guide readers on how to easily install the Laravel framework. Laravel is a powerful PHP framework that speeds up the development process of web applications. This tutorial covers the installation process from system requirements to configuring databases and setting up routing. By following these steps, readers can quickly and efficiently lay a solid foundation for their Laravel project.

MySQL vs. Other Programming Languages: A Comparison MySQL vs. Other Programming Languages: A Comparison Apr 19, 2025 am 12:22 AM

Compared with other programming languages, MySQL is mainly used to store and manage data, while other languages ​​such as Python, Java, and C are used for logical processing and application development. MySQL is known for its high performance, scalability and cross-platform support, suitable for data management needs, while other languages ​​have advantages in their respective fields such as data analytics, enterprise applications, and system programming.

See all articles