search
Homephp教程php手册FLEAPHP框架下Mysqli连接扩展

公司老的CRM系统是基于FLEAPHP,这玩意老早就不更新了,当php升级到5.5后,系统会提示mysql_connect函数即将被废弃,建议跟换mysqli或pdo,nnd逼我换框架么,好吧我只是随便说说,还是自己动手,丰衣足食。 新增一个Mysqli.php,修改Abstract.php文件。 使用方

公司老的CRM系统是基于FLEAPHP,这玩意老早就不更新了,当php升级到5.5后,系统会提示mysql_connect函数即将被废弃,建议跟换mysqli或pdo,nnd逼我换框架么,好吧我只是随便说说,还是自己动手,丰衣足食。
新增一个 Mysqli.php,修改Abstract.php 文件。
使用方法:
将两个文件放到"FLEA\Db\Driver\"目录下,覆盖即可。
Ps:Abstract.php只是做了一个很小的兼容性修改,不影响其他功能。 FleaPHP
<?php
/**
 * 定义 FLEA_Db_Driver_Mysqli 驱动 基于FLEA_Db_Driver_Mysql 修改
 * by 豚鼠窝窝 2014.05.07
 * maophp@qq.com
*/

// {{{ includes
FLEA::loadClass('FLEA_Db_Driver_Abstract');
// }}}

class FLEA_Db_Driver_Mysqli extends FLEA_Db_Driver_Abstract
{
    var $NEXT_ID_SQL    = 'UPDATE %s SET id = LAST_INSERT_ID(id + 1)';
    var $CREATE_SEQ_SQL = 'CREATE TABLE %s (id INT NOT NULL)';
    var $INIT_SEQ_SQL   = 'INSERT INTO %s VALUES (%s)';
    var $DROP_SEQ_SQL   = 'DROP TABLE %s';
    var $META_COLUMNS_SQL = 'SHOW FULL COLUMNS FROM %s';
    var $PARAM_STYLE = DBO_PARAM_QM;
    var $HAS_INSERT_ID  = true;
    var $HAS_AFFECTED_ROWS = true;
    var $_mysqlVersion = null;

    function connect($dsn = false)
    {
        $this->lasterr = null;
        $this->lasterrcode = null;

        if ($this->conn && $dsn == false) { return true; }
        if (!$dsn) {
            $dsn = $this->dsn;
        } else {
            $this->dsn = $dsn;
        }
        if (isset($dsn['port']) && $dsn['port'] != '') {
            $host = $dsn['host'] . ':' . $dsn['port'];
        } else {
            $host = $dsn['host'];
        }
        if (!isset($dsn['login'])) { $dsn['login'] = ''; }
        if (!isset($dsn['password'])) { $dsn['password'] = ''; }
        if (!empty($dsn['options'])) {
            $this->conn = mysqli_connect($host, $dsn['login'], $dsn['password'], false, $dsn['options']);
        } else {
            $this->conn = mysqli_connect($host, $dsn['login'], $dsn['password']);
        }

        if (!$this->conn) {
            FLEA::loadClass('FLEA_Db_Exception_SqlQuery');
            return __THROW(new FLEA_Db_Exception_SqlQuery("mysqli_connect('{$host}', '{$dsn['login']}') failed!", mysqli_error(), mysqli_errno()));
        }

        if (!empty($dsn['database'])) {
            if (!$this->selectDb($dsn['database'])) { return false; }
        }

        $this->_mysqlVersion = $this->getOne('SELECT VERSION()');
        if (isset($dsn['charset']) && $dsn['charset'] != '') {
            $charset = $dsn['charset'];
        } else {
            $charset = FLEA::getAppInf('databaseCharset');
        }
        if ($this->_mysqlVersion >= '4.1' && $charset != '') {
            if (!$this->execute("SET NAMES '" . $charset . "'")) { return false; }
        }
	if ($this->_mysqlVersion >= '5.0') {
            $this->HAS_SAVEPOINT = true;
        }
        return true;
    }

    function close()
    {
        if ($this->conn) { mysqli_close($this->conn); }
        parent::close();
    }

    function selectDb($database)
    {
        if (!mysqli_select_db( $this->conn, $database)) {
            FLEA::loadClass('FLEA_Db_Exception_SqlQuery');
            return __THROW(new FLEA_Db_Exception_SqlQuery("SELECT DATABASE: '{$database}' FAILED!", mysqli_error($this->conn), mysqli_errno($this->conn)));
        }
        return true;
    }

    function execute($sql, $inputarr = null, $throw = true)
    {
        if (is_array($inputarr)) {
            $sql = $this->bind($sql, $inputarr);
        }
        if ($this->enableLog) {
            $this->log[] = $sql;
            log_message("sql: {$sql}", 'debug');
        }

        $this->querycount++;
        $result =  mysqli_query($this->conn, $sql,MYSQLI_USE_RESULT);
        if ($result !== false) {
            $this->lasterr = null;
            $this->lasterrcode = null;
            return $result;
        }
        $this->lasterr = mysqli_error($this->conn);
        $this->lasterrcode = mysqli_errno($this->conn);

        if ($throw) {
            FLEA::loadClass('FLEA_Db_Exception_SqlQuery');
            __THROW(new FLEA_Db_Exception_SqlQuery($sql, $this->lasterr, $this->lasterrcode));
        }
        return false;
    }

    function qstr($value)
    {
        if (is_int($value) || is_float($value)) { return $value; }
        if (is_bool($value)) { return $value ? $this->TRUE_VALUE : $this->FALSE_VALUE; }
        if (is_null($value)) { return $this->NULL_VALUE; }
        return "'" . mysqli_real_escape_string($this->conn, $value) . "'";
    }

    function qtable($tableName, $schema = null)
    {
        return $schema != '' ? "`{$schema}`.`{$tableName}`" : "`{$tableName}`";
    }

    function qfield($fieldName, $tableName = null, $schema = null)
    {
        $fieldName = ($fieldName == '*') ? '*' : "`{$fieldName}`";
        return $tableName != '' ? $this->qtable($tableName, $schema) . '.' . $fieldName : $fieldName;
    }

    function _insertId()
    {
        return mysqli_insert_id($this->conn);
    }

    function _affectedRows()
    {		
        return mysqli_affected_rows($this->conn);
    }

    function fetchRow($res)
    {
        return mysqli_fetch_row($res);
    }

    function fetchAssoc($res)
    { 
	
        return mysqli_fetch_assoc($res);
    }

    function freeRes($res)
    {
        return mysqli_free_result($res);
    }

    function selectLimit($sql, $length = null, $offset = null)
    {
        if (!is_null($offset)) {
            $sql .= " LIMIT " . (int)$offset;
            if (!is_null($length)) {
                $sql .= ', ' . (int)$length;
            } else {
                $sql .= ', 4294967294';
            }
        } elseif (!is_null($length)) {
            $sql .= " LIMIT " . (int)$length;
	}
	return $this->execute($sql);

    }

    function metaColumns($table)
    {
        /**
         *  C CHAR 或 VARCHAR 类型字段
         *  X TEXT 或 CLOB 类型字段
         *  B 二进制数据(BLOB)
         *  N 数值或者浮点数
         *  D 日期
         *  T TimeStamp
         *  L 逻辑布尔值
         *  I 整数
         *  R 自动增量或计数器
         */
        static $typeMap = array(
            'BIT'           => 'I',
            'TINYINT'       => 'I',
            'BOOL'          => 'L',
            'BOOLEAN'       => 'L',
            'SMALLINT'      => 'I',
            'MEDIUMINT'     => 'I',
            'INT'           => 'I',
            'INTEGER'       => 'I',
            'BIGINT'        => 'I',
            'FLOAT'         => 'N',
            'DOUBLE'        => 'N',
            'DOUBLEPRECISION' => 'N',
            'FLOAT'         => 'N',
            'DECIMAL'       => 'N',
            'DEC'           => 'N',

            'DATE'          => 'D',
            'DATETIME'      => 'T',
            'TIMESTAMP'     => 'T',
            'TIME'          => 'T',
            'YEAR'          => 'I',

            'CHAR'          => 'C',
            'NCHAR'         => 'C',
            'VARCHAR'       => 'C',
            'NVARCHAR'      => 'C',
            'BINARY'        => 'B',
            'VARBINARY'     => 'B',
            'TINYBLOB'      => 'X',
            'TINYTEXT'      => 'X',
            'BLOB'          => 'X',
            'TEXT'          => 'X',
            'MEDIUMBLOB'    => 'X',
            'MEDIUMTEXT'    => 'X',
            'LONGBLOB'      => 'X',
            'LONGTEXT'      => 'X',
            'ENUM'          => 'C',
            'SET'           => 'C',
        );

        $rs = $this->execute(sprintf($this->META_COLUMNS_SQL, $table));
        if (!$rs) { return false; }
        $retarr = array();
        while (($row = mysqli_fetch_assoc($rs))) {
            $field = array();
            $field['name'] = $row['Field'];
            $type = $row['Type'];

            $field['scale'] = null;
            $queryArray = false;
            if (preg_match('/^(.+)\((\d+),(\d+)/', $type, $queryArray)) {
                $field['type'] = $queryArray[1];
                $field['maxLength'] = is_numeric($queryArray[2]) ? $queryArray[2] : -1;
                $field['scale'] = is_numeric($queryArray[3]) ? $queryArray[3] : -1;
            } elseif (preg_match('/^(.+)\((\d+)/', $type, $queryArray)) {
                $field['type'] = $queryArray[1];
                $field['maxLength'] = is_numeric($queryArray[2]) ? $queryArray[2] : -1;
            } elseif (preg_match('/^(enum)\((.*)\)$/i', $type, $queryArray)) {
                $field['type'] = $queryArray[1];
                $arr = explode(",",$queryArray[2]);
                $field['enums'] = $arr;
                $zlen = max(array_map("strlen",$arr)) - 2; // PHP >= 4.0.6
                $field['maxLength'] = ($zlen > 0) ? $zlen : 1;
            } else {
                $field['type'] = $type;
                $field['maxLength'] = -1;
            }
            $field['simpleType'] = $typeMap[strtoupper($field['type'])];
            // if ($field['simpleType'] == 'C' && $field['maxLength'] > 250) {
                // $field['simpleType'] = 'X';
            // }
            $field['notNull'] = ($row['Null'] != 'YES');
            $field['primaryKey'] = ($row['Key'] == 'PRI');
            $field['autoIncrement'] = (strpos($row['Extra'], 'auto_increment') !== false);
            if ($field['autoIncrement']) { $field['simpleType'] = 'R'; }
            $field['binary'] = (strpos($type,'blob') !== false);
            $field['unsigned'] = (strpos($type,'unsigned') !== false);

            if ($field['type'] == 'tinyint' && $field['maxLength'] == 1) {
                $field['simpleType'] = 'L';
            }

            if (!$field['binary']) {
                $d = $row['Default'];
                if ($d != '' && $d != 'NULL') {
                    $field['hasDefault'] = true;
                    $field['defaultValue'] = $this->setValueByType($d, $field['simpleType']);
                } else {
                    $field['hasDefault'] = false;
                }
            }

            $field['description'] = isset($row['Comment']) ? $row['Comment'] : '';

            $retarr[strtoupper($field['name'])] = $field;
        }
        mysqli_free_result($rs);
        return $retarr;
    }

    function metaTables($pattern = null, $schema = null)
    {
        $sql = 'SHOW TABLES';
		if (!empty($schema)) {
		    $sql .= " FROM {$schema}";
		}
		if (!empty($pattern)) {
		    $sql .= ' LIKE ' . $this->qstr($schema);
		}
		$res = $this->execute($sql, null, false);
		$tables = array();
		while (($row = $this->fetchRow($res))) {
		   $tables[] = reset($row);
		}
		$this->freeRes($res);
		return $tables;
    }

    function _startTrans()
    {
        $this->execute('START TRANSACTION');
    }

    function _completeTrans($commitOnNoErrors = true)
    {
        if ($this->_hasFailedQuery == false && $commitOnNoErrors) {
            $this->execute('COMMIT');
        } else {
            $this->execute('ROLLBACK');
        }
    }

}


Statement
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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment