mysql操作クラスライブラリ--抜粋

60084 ワード

<!--?php



/**

  +----------------------------------

 * MySQL    

  +----------------------------------

 * @author       <www.imaben.com-->

  +----------------------------------

 * @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
' . 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
' . 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
' . 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
' . 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
'; } $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、 */ ?>