php教程 php手册 mysql操作类库1.2

mysql操作类库1.2

Jun 06, 2016 pm 08:09 PM
mysql 작동하다 변화 클래스 라이브러리

又经过了一次小的改动,现把最新版发出来: ?php/** +---------------------------------- * MySQL操作类库 +---------------------------------- * @author 马犇 +---------------------------------- * @version 1.2 (2013-5-31) +-----------------------

又经过了一次小的改动,现把最新版发出来:

<?php /**
  +----------------------------------
 * MySQL操作类库
  +----------------------------------
 * @author    马犇 
  +----------------------------------
 * @version   1.2 (2013-5-31)
  +----------------------------------
 */
include (dirname(__FILE__) . DIRECTORY_SEPARATOR . 'config.php');
define('CLIENT_MULTI_RESULTS', 131072);
class mysql {
    /* 主机地址 */
    private $Host = '127.0.0.1';
     /* 数据库名称 */
    private $dbName = DB_NAME;
    /* 用户名 */
    private $UserName = DB_USER;
    /* 连接密码 */
    private $Password = DB_PWD;
    /* 数据库编码 */
    private $dbCharSet = 'utf8';
    /* 错误信息 */
    private $errorMsg;
    /* 最后一次执行的SQL */
    private $lastSql;
    /* 字段信息 */
    private $fields = array();
    /* 最后一次插入的ID */
    public $lastInsID = null;
    /* 数据库连接ID */
    private $linkID = 0;
    /* 当前查询ID */
    private $queryID = null;
	/*主键*/
	private $pk = null;
    public function __construct($DBName = '') {
        if ($DBName != '')
            $this->dbName = $DBName;
        $this->connect();
    }
    /**
      +----------------------------------------------------------
     * 连接数据库方法
      +----------------------------------------------------------
     * @access public
      +----------------------------------------------------------
     */
    public function connect() {
        if ($this->linkID == 0) {
            $this->linkID = mysql_connect($this->Host, $this->UserName, $this->Password, true, CLIENT_MULTI_RESULTS);
            if (!$this->linkID) {
                $this->errorMsg = '数据库连接错误\r\n' . mysql_error();
                $this->halt();
            }
        }
        if (!mysql_select_db($this->dbName, $this->linkID)) {
            $this->errorMsg = '打开数据库失败' . mysql_error($this->linkID);
            $this->halt('打开数据库失败');
        }
        $dbVersion = mysql_get_server_info($this->linkID);
        if ($dbVersion >= "4.1") {
            //使用UTF8存取数据库 需要mysql 4.1.0以上支持
            mysql_query("SET NAMES '" . $this->dbCharSet . "'", $this->linkID);
        }
        //设置CharSet
        mysql_query('set character set \'' . $this->dbCharSet . '\'', $this->linkID);
        //设置 sql_model
        if ($dbVersion > '5.0.1') {
            mysql_query("SET sql_mode=''", $this->linkID);
        }
    }
    /**
      +----------------------------------------------------------
     * 释放查询结果
      +----------------------------------------------------------
     * @access public
      +----------------------------------------------------------
     */
    public function free() {
		if($this->queryID != null)
        	mysql_free_result($this->queryID);
        $this->queryID = null;
    }
    /**
      +----------------------------------------------------------
     * 执行语句
      +----------------------------------------------------------
     * @access public
      +----------------------------------------------------------
     * @param string $sql  sql指令
      +----------------------------------------------------------
     * @return bool or resource
      +----------------------------------------------------------
     */
    public function execute($sql) {
        if ($this->linkID == 0)
            $this->connect();
        $this->lastSql = $sql;
        $this->queryID = mysql_query($sql);
        if (false == $this->queryID) {
            $this->errorMsg = 'SQL语句执行失败\r\n' . mysql_error($this->linkID);
            return false;
        } else {
            return $this->queryID;
        }
    }
    /**
      +----------------------------------------------------------
     * 获取记录集的行数
      +----------------------------------------------------------
     * @access public
      +----------------------------------------------------------
     * @param string $sql  sql指令 可为空
     * 如为空:返回上一结果集记录数
     * 如不为空:返回当前sql语句的记录数 
      +----------------------------------------------------------
     * @return integer
      +----------------------------------------------------------
     */
    public function getRowsNum($sql = '') {
        if ($this->linkID == 0) {
            $this->connect();
        }
        if ($sql != '') {
            $this->execute($sql);
        }
        return mysql_num_rows($this->queryID);
    }
    /**
      +----------------------------------------------------------
     * 表单数据直接插入到数据表中
      +----------------------------------------------------------
     * @access public
      +----------------------------------------------------------
     * @param string $tableName 数据表名
      +----------------------------------------------------------
     * @return 执行成功返回插入记录的索引记录,失败返回false
      +----------------------------------------------------------
     */
    public function form2db($tableName) {
        $_POST["add_time"] = date('Y-m-d H:i:s');
		$data = $_POST;
        $this->fields = $this->getFields($tableName);
        $data = $this->_facade($data);
        if ($this->insert($tableName, $data)) {
            return $this->lastInsID;
        } else {
            return false;
        }
    }
    /**
      +----------------------------------------------------------
     * 数据直接插入到数据表中
      +----------------------------------------------------------
     * @access public
      +----------------------------------------------------------
     * @param string $tableName 数据表名
      +----------------------------------------------------------
     * @param array $data 插入的数据 数据键名对应字段名,键值对应值
      +----------------------------------------------------------
     * @return boolean
      +----------------------------------------------------------
     */
    public function insert($tableName, $data) {
        $values = $fields = array();
        foreach ($data as $key => $val) {
            $value = '\'' . addslashes($val) . '\'';
            if (is_scalar($value)) { // 过滤非标量数据
                $values[] = $value;
                $fields[] = $key;
            }
        }
        $sql = 'INSERT INTO ' . trim($tableName) . '(' . implode(',', $fields) . ') VALUES(' . implode(',', $values) . ')';
        if ($this->execute($sql)) {
            $this->errorMsg = '插入失败\r\n' . mysql_error($this->linkID);
            $this->lastInsID = mysql_insert_id($this->linkID);
            return true;
        } else {
            return false;
        }
    }
    /**
      +----------------------------------------------------------
     * 更新操作
      +----------------------------------------------------------
     * @access public
      +----------------------------------------------------------
     * @param string $tableName 数据表名
      +----------------------------------------------------------
     * @param array $data 插入的数据 数据键名对应字段名,键值对应值
      +----------------------------------------------------------
     * @param array $condition 更新条件,为安全起见,不能为空
      +----------------------------------------------------------
     * @param array $isForm 可为空,缺省为true
     * 如果为true,会当成表单更新数据表来处理,自动映射字段
     * 如果为false,会当成普通的更新来处理,不会自动映射字段
      +----------------------------------------------------------
     * @return boolean
      +----------------------------------------------------------
     */
    public function update($tableName, $data, $condition, $isForm = true) {
        if (empty($condition)) {
            $this->errorMsg = '没有设置更新条件';
            return false;
		}
		//处理分解condition
		if(is_array($condition)){
			$condition = self::_parseCondition($condition);
		}
        if ($isForm) {
            $this->fields = $this->getFields($tableName);
            $data = $this->_facade($data);
        }
        $sql = 'UPDATE ' . trim($tableName) . ' SET ';
        foreach ($data as $key => $val) {
            $sql .= $key . '=\'' . $val . '\',';
        }
        $sql = substr($sql, 0, strlen($sql) - 1);
        $sql .= ' WHERE ' . $condition;
        if ($this->execute($sql)) {
            return true;
        } else {
            $this->errorMsg = '更新失败\r\n' . mysql_error($this->linkID);
            return false;
        }
    }
    /**
      +----------------------------------------------------------
     *  删除操作
      +----------------------------------------------------------
     * @access public
      +----------------------------------------------------------
     * @param string $tableName 数据表名
      +----------------------------------------------------------
     * @param array $condition 更新条件,为安全起见,不能为空
      +----------------------------------------------------------
     * @return boolean
      +----------------------------------------------------------
     */
    public function delete($tableName, $condition) {
		//处理分解condition
		if(is_array($condition)){
			$condition = self::_parseCondition($condition);
		}
        $sql = 'delete from ' . $tableName . ' where 1=1 and ' . $condition;
        if (!$this->execute($sql))
            return false;
        return true;
    }
    /**
     +----------------------------------------------------------
     * 利用__call魔术方法实现一些特殊的Model方法
     +----------------------------------------------------------
     * @access public
     +----------------------------------------------------------
     * @param string $method 方法名称
     * @param array $args 调用参数
     +----------------------------------------------------------
     * @return mixed
     +----------------------------------------------------------
     */
    public function __call($method,$args){
        /*根据某个字段获取记录字段的值
         * 例1:getFieldByid(student_info,100,name)---获取学生表中id为100的学生姓名
         * 例2:getFieldByxh(student_info,201215030223,address)---获取学生表中学号为201015030223的地址
         * 注:"getFieldBy"不区分大小写,后面的字段名区分大小写
		 * 返回值:string
         */
        if(strtolower(substr($method,0,10)) == 'getfieldby'){
            $name = substr($method,10);
            $sql = 'select `'.$args[2].'` from '.$args[0].' where '.$name.'=\''.$args[1].'\'';
			if($this->execute($sql)){
            	$row = mysql_fetch_array($this->queryID);
            	return $row[0];
			}else{
				return false;
			}
        }
		 /*根据某个字段和值获取某条记录
         * 例1:getByid(student_info,100)---获取学生表中id为100的学生信息
         * 例2:getByxh(student_info,201215030223)---获取学生表中学号为201015030223的学生信息
         * 注:"getBy"不区分大小写,后面的字段名区分大小写
		 * 返回值:array
         */
		elseif(strtolower(substr($method,0,5)) == 'getby'){
			$ret = array();
			$name = substr($method,5);
			$sql = 'select * from '.$args[0].' where '.$name.'=\''.$args[1].'\'';
			if($this->execute($sql)){
				$row = mysql_fetch_array($this->queryID);
				return $row;
			}else{
				return false;
			}
		}
    }
    /**
      +----------------------------------------------------------
     *  弹出错误提示,并终止运行
      +----------------------------------------------------------
     * @access public
      +----------------------------------------------------------
     * @param string $msg 错误消息,可为空
      +----------------------------------------------------------
     */
    public static function halt($msg = '') {
        if ($msg != '') {
            $msg .= '\r\n';
        }
		$error = mysql_error();
        die($msg);
    }
    /**
      +----------------------------------------------------------
     *  获取最后一次查询ID
      +----------------------------------------------------------
     * @access public
      +----------------------------------------------------------
     */
	 public function getQueryId(){
		 return $this->queryID;
	 }
	 /**
      +----------------------------------------------------------
     *  获取最后一次数据库操作错误信息
      +----------------------------------------------------------
     * @access public
      +----------------------------------------------------------
     */
    public function getLastError() {
        return $this->errorMsg;
    }
    /**
      +----------------------------------------------------------
     *  获取最后一次执行的SQL语句
      +----------------------------------------------------------
     * @access public
      +----------------------------------------------------------
     */
    public function getLastSql() {
        return $this->lastSql;
    }
    /**
      +----------------------------------------------------------
     *  获取最后一次插入数据库记录的索引ID号
      +----------------------------------------------------------
     * @access public
      +----------------------------------------------------------
     */
    public function getLastInsID() {
        return $this->lastInsID;
    }
    /**
      +----------------------------------------------------------
     *  获取上一次操作影响的行数
      +----------------------------------------------------------
     * @access public
      +----------------------------------------------------------
     */
    public function getAffectedRows() {
        return mysql_affected_rows($this->linkID);
    }
    /**
      +----------------------------------------------------------
     * 取得数据表的字段信息
      +----------------------------------------------------------
     * @access public
      +----------------------------------------------------------
     */
    public function getFields($tableName) {
        $result = array();
        $this->execute('SHOW COLUMNS FROM ' . $this->parseKey($tableName));
        while ($row = mysql_fetch_array($this->queryID)) {
            $result[] = $row;
        }
        $info = array();
        if ($result) {
            foreach ($result as $key => $val) {
                $info[$val['Field']] = array(
                    'name' => $val['Field'],
                    'type' => $val['Type'],
                    'notnull' => (bool) ($val['Null'] === ''), // not null is empty, null is yes
                    'default' => $val['Default'],
                    'primary' => (strtolower($val['Key']) == 'pri'),
                    'autoinc' => (strtolower($val['Extra']) == 'auto_increment'),
                );
            }
        }
        return $info;
    }
    /**
      +----------------------------------------------------------
     * 字段和表名处理添加`
      +----------------------------------------------------------
     * @access protected
      +----------------------------------------------------------
     * @param string $key
      +----------------------------------------------------------
     * @return string
      +----------------------------------------------------------
     */
    protected function parseKey(&$key) {
        $key = trim($key);
        if (false !== strpos($key, ' ') || false !== strpos($key, ',') || false !== strpos($key, '*') || false !== strpos($key, '(') || false !== strpos($key, '.') || false !== strpos($key, '`')) {
            //如果包含* 或者 使用了sql方法 则不作处理
        } else {
            $key = '`' . $key . '`';
        }
        return $key;
    }
    /**
      +----------------------------------------------------------
     * 对保存到数据库的数据进行处理
      +----------------------------------------------------------
     * @access protected
      +----------------------------------------------------------
     * @param mixed $data 要操作的数据
      +----------------------------------------------------------
     * @return boolean
      +----------------------------------------------------------
     */
    private function _facade($data) {
        // 检查非数据字段
        if (!empty($this->fields)) {
            foreach ($data as $key => $val) {
                if (!array_key_exists($key, $this->fields)) {
                    unset($data[$key]);
                }
            }
        }
        return $data;
    }
	public function close(){
		mysql_close($this->linkID);
	}
	public function __destruct(){
		$this->close();
	}
    /*
    ** 2013.5.25新增
    */
	public function getPk($table){
		//将pk置为空
		$this->pk = null;
		$result = $this->getFields($table);
		foreach($result as $key => $val){
			if($val['primary']){
				$this->pk = $key;
				break;
			}
		}
		return $this->pk;
	}
	public function fetch(&$rst = null , $array_type = MYSQL_ASSOC){
		if($rst == null){
			$rst = $this->queryID;
		}
		if($this->queryID)
			return mysql_fetch_array($rst , $array_type);
		else
			return false;
	}
    //分解条件
    private function _parseCondition($condition , $operator='AND'){
        $return = '';
        if (is_array($condition)) {
            $index = 0;
            foreach ($condition as $key => $value) {
                if ($index) {
                    $return .= " ".$operator;
                }
                $return .= "`{$key}`='{$value}'";
                $index++;
            }
            return $return;
        }else{
            return false;
        }
    }
    /*事务处理开始*/
    public function beginTransaction(){
        $this->execute("START TRANSACTION");
    }
    public function commit(){
        $this->execute("COMMIT");  
    }
    public function rollback(){
        $this->execute("ROLLBACK");
    }
	/*事务处理结束*/
	//根据条件查找一条记录
	public function find($table,$condition = null,$field = null){
	    if(is_array($condition)){
	        $condition = self::_parseCondition($condition);
	    }
		//处理condition和field
		$condition = $condition == null ? null : (is_array($condition) ? self::_parseCondition($condition) : $condition);
		$field = $field == null ? '*' : (is_array($field) ? implode(",",$field) : $field);
		$sql = 'SELECT ' . $field . ' FROM '.$table;
		if($condition != null){
			$sql .= " WHERE " . $condition;
		}
		return $this->findOneBySql($sql);
	}
	//查找所有记录
	public function findAll($table,$condition = null,$field = null){
		if(is_array($condition)){
	        $condition = self::_parseCondition($condition);
	    }
		//处理condition和field
		$condition = $condition == null ? null : (is_array($condition) ? self::_parseCondition($condition) : $condition);
		$field = $field == null ? '*' : (is_array($field) ? implode(",",$field) : $field);
		$sql = 'SELECT ' . $field . ' FROM '.$table;
		if($condition != null){
			$sql .= " WHERE " . $condition;
		}
		return $this->findallBySql($sql);
	}
	public function findOneBySql($sql){
		$sql .= " LIMIT 1";
		$this->execute($sql);
		return $this->fetch();
	}
	public function findAllBySql($sql){
		$rows = array();
		$this->execute($sql);
		while($row = $this->fetch()){
			$rows[] = $row;
		}
		return $rows;
	}
	public function findByPk($table,$_pk){
		$pk = $this->getPk($table);
		if($pk == null){
			$this->errorMsg = "未找到该表的主键";
			return false;
		}else{
			return $this->find($table,array(
				$pk => $_pk
			));
		}
	}
	public function deleteByPk($table,$_pk){
		$pk = $this->getPk($table);
		if($pk == null){
			$this->errorMsg = "未找到该表的主键";
			return false;
		}else{
			$sql = "DELETE FROM ".$table." WHERE `{$pk}`='{$_pk}'";
			return $this->delete($table,array(
				$pk => $_pk
			));
		}
	}
}
/*
 * 类库更新日志  2013.5.25 
 * 1、update delete操作中的条件可以设置为数组形式$key=>$value
 * 2、增加事务处理功能(只针对innodb引擎)
 * 3、增加根据条件查找一条记录
 * 4、增加根据条件查找所有记录
 * 5、增加根据主键查找记录
 * 6、增加根据主键删除记录
 */
?>
로그인 후 복사
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

MySQL 8.4에서 mysql_native_password가 로드되지 않음 오류를 수정하는 방법 MySQL 8.4에서 mysql_native_password가 로드되지 않음 오류를 수정하는 방법 Dec 09, 2024 am 11:42 AM

MySQL 8.4(2024년 최신 LTS 릴리스)에 도입된 주요 변경 사항 중 하나는 &quot;MySQL 기본 비밀번호&quot; 플러그인이 더 이상 기본적으로 활성화되지 않는다는 것입니다. 또한 MySQL 9.0에서는 이 플러그인을 완전히 제거합니다. 이 변경 사항은 PHP 및 기타 앱에 영향을 미칩니다.

Astar 스테이킹 원칙, 수입 해체, 에어드랍 프로젝트 및 전략 및 운영 보모 수준 전략 Astar 스테이킹 원칙, 수입 해체, 에어드랍 프로젝트 및 전략 및 운영 보모 수준 전략 Jun 25, 2024 pm 07:09 PM

목차 Astar Dapp 스테이킹 원리 스테이킹 수익 잠재적 에어드랍 프로젝트 해체: AlgemNeurolancheHealThreeAstar Degens DAOVeryLongSwap 스테이킹 전략 및 운영 "AstarDapp 스테이킹"이 올해 초 V3 버전으로 업그레이드되었으며 스테이킹 수익에 많은 조정이 이루어졌습니다. 규칙. 현재 첫 번째 스테이킹 주기는 종료되었으며 두 번째 스테이킹 주기의 "투표" 하위 주기가 막 시작되었습니다. '추가 보상' 혜택을 받으려면 이 중요한 단계(6월 26일까지 지속 예정, 5일 미만 남았음)를 파악해야 합니다. 아스타 스테이킹 수익을 자세하게 분석해보겠습니다.

PHP가 MySQL에 연결된 후 페이지가 비어 있습니다. 유효하지 않은 다이 () 함수의 이유는 무엇입니까? PHP가 MySQL에 연결된 후 페이지가 비어 있습니다. 유효하지 않은 다이 () 함수의 이유는 무엇입니까? Apr 01, 2025 pm 03:03 PM

PHP가 MySQL에 연결 한 후 페이지가 비어 있고 Die () 함수가 실패한 이유가 있습니다. PHP와 MySQL 데이터베이스 간의 연결을 배울 때는 종종 혼란스러운 것들이 발생합니다 ...

램프 아키텍처에서 Node.js 또는 Python 서비스를 효율적으로 통합하는 방법은 무엇입니까? 램프 아키텍처에서 Node.js 또는 Python 서비스를 효율적으로 통합하는 방법은 무엇입니까? Apr 01, 2025 pm 02:48 PM

많은 웹 사이트 개발자는 램프 아키텍처에서 Node.js 또는 Python 서비스를 통합하는 문제에 직면 해 있습니다. 기존 램프 (Linux Apache MySQL PHP) 아키텍처 웹 사이트 요구 사항 ...

PC 및 모바일 측면에서 동일한 페이지를 공유하고 캐시 문제를 처리하는 방법은 무엇입니까? PC 및 모바일 측면에서 동일한 페이지를 공유하고 캐시 문제를 처리하는 방법은 무엇입니까? Apr 01, 2025 pm 01:57 PM

PC 및 모바일 측면에서 동일한 페이지를 공유하고 캐시 문제를 처리하는 방법은 무엇입니까? Baota 배경, PC 측면을 만드는 방법 및 ...

거래 공제 잔액과 결합 된 PHP 낙관적 잠금 실패 : 동시성 상황에서 잔액이 올바르게 공제되는지 확인하는 방법은 무엇입니까? 거래 공제 잔액과 결합 된 PHP 낙관적 잠금 실패 : 동시성 상황에서 잔액이 올바르게 공제되는지 확인하는 방법은 무엇입니까? Mar 31, 2025 pm 11:42 PM

이 기사에서 PHP 낙관적 잠금 및 거래와 함께 균형을 공제하는 문제에 대한 자세한 설명은 PHP, 낙관적 잠금 및 데이터베이스 트랜잭션을 사용한 균형 공제를 자세히 분석합니다.

Redis 내보내기 서비스를 사용하여 Redis Droplet 모니터링 Redis 내보내기 서비스를 사용하여 Redis Droplet 모니터링 Jan 06, 2025 am 10:19 AM

Redis 데이터베이스를 효과적으로 모니터링하는 것은 최적의 성능을 유지하고 잠재적인 병목 현상을 식별하며 전반적인 시스템 안정성을 보장하는 데 필수적입니다. Redis 내보내기 서비스는 다음을 사용하여 Redis 데이터베이스를 모니터링하도록 설계된 강력한 유틸리티입니다.

See all articles