+ -
当前位置:首页 → 问答吧 → 我的数据库类[PHP5]

我的数据库类[PHP5]

时间:2007-05-27

来源:互联网

复制内容到剪贴板
代码:
<?php
/**
* @brief 数据库实际实例类 * @author feeling <[email][email protected][/email]>
* @date 2007-5-26 13:33
* @version 1.0
*/
class Database
{
        private static $instance = NULL;        /**<  Instance of the database */

        /**
         * @brief Constructor
         * @param $database_type Type of the main database server. It could be one of 'ImMySQL', 'MySQL4'. At same time, a filename and class name with the same name would be saved in the directory which this file saved
         * @param $config Configure for database server
         * @return The database object
         */
        private function __construct($database_type, $config = NULL)
        {
                switch (strtolower($database_type)) {
                        case 'mysqli': $type = 'ImMySQL'; break;
                        case 'mysql4': $type = 'MySQL4'; break;
                        default: $type = 'ImMySQL'; break;
                }
                include_once(dirname(__FILE__) . '/IDatabase.php');
                $database_file = dirname(__FILE__) . '/' . $type . '.php';
                if (TRUE == @file_exists($database_file)) {
                        include_once($database_file);
                        $tmp = new $type();
                        if (NULL !== $config) $tmp->setConfig($config);
                        return $tmp;
                }
                return FALSE;
        }

        /**
         * @brief The singleton method
         * @param $database_type Type of the main database server. It could be one of 'ImMySQL', 'MySQL4'. At same time, a filename and class name with the same name would be saved in the directory which this file saved
         * @param $config Configure for database server
         * @return The database object
         */
        public static function getInstance($database_type = 'mysql', $config = NULL)
        {
                if (NULL == self::$instance) {
                        $class_name = __CLASS__;
                        self::$instance = new $class_name($database_type, $config);
                }
                return self::$instance;
        }
}
?>
[ 本帖最后由 cfeeling 于 2007-5-27 10:58 编辑 ]

作者: cfeeling   发布时间: 2007-05-27

数据库接口定义:
复制内容到剪贴板
代码:
<?php
/**
* @brief Interface define for Database operating
* @author [email][email protected][/email]
* @date 2007-5-26 13:52
* @version 1.0
**/
interface IDatabase
{
        /**
         * @brief Open a connection to a MySQL Server
         * @return Returns a MySQL connection on success, or FALSE on failure
         **/
        public function connect();
        /**
         * @brief Close MySQL connection
         * @param $connect_id The MySQL connection. If it was not specified, the current connection is assumed
         * @return Returns TRUE on success or FALSE on failure. If using a persistent connection, it always return TRUE
         **/
        public function close($connect_id = NULL);
        /**
         * @brief Send a MySQL query
         * @param $query_string SQL query sentence
         * @param $connect_id The MySQL connection. If it was not specified, the current connection is assumed
         * @return For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, it returns a resource on success, or FALSE on error.<br />For other type of SQL statements, UPDATE, DELETE, DROP, etc, it returns TRUE on success or FALSE on error.
         **/
        public function query($query_string, $connect_id = NULL);
        /**
         * @brief Escapes special characters in a string for use in a SQL statement
         * @param $query_string The string that is to be escaped
         * @param $connect_id The MySQL connection. If it was not specified, the current connection is assumed
         * @return Returns the escaped string, or FALSE on error
         **/
        public function escape($query_string, $connect_id = NULL);
        /**
         * @brief Free result memory
         * @param $query_id The query, If it was not specified, the current query is assumed
         * @return Returns TRUE on success or FALSE on failure
         **/
        public function freeResult($query_id = NULL);
        /**
         * @brief Fetch a result row
         * @param $query_type The type of array that is to be fetched. It's a constant and can take the following values: ASSOC, NUM, and the default value of BOTH.
         * @param $query_id The query, If it was not specified, the current query is assumed
         * @return Returns an array of strings that corresponds to the fetched row, or FALSE if there are no more rows.
         **/
        public function fetchArray($query_type = 'BOTH', $query_id = NULL);
        /**
         * @brief Fetch all result rows
         * @param $query_type The type of array that is to be fetched. It's a constant and can take the following values: ASSOC, NUM, and the default value of BOTH.
         * @param $query_id The query, If it was not specified, the current query is assumed
         * @return Returns an array of strings that corresponds to all fetched rows, or FALSE if there are no more rows.
         **/
        public function fetchArrayBat($query_type = 'BOTH', $query_id = NULL);
        /**
         * @brief Get the ID generated from the previous INSERT operation
         * @param $connect_id The MySQL connection. If it was not specified, the current connection is assumed
         * @return The ID generated for an AUTO_INCREMENT column by the previous INSERT query on success, 0 if the previous query does not generate an AUTO_INCREMENT value, or FALSE if no MySQL connection was established.
         **/
        public function getInsertId($connect_id = NULL);
        /**
         * @brief Get number of affected rows in previous MySQL operation
         * @param $connect_id The MySQL connection. If it was not specified, the current connection is assumed
         * @return Returns the number of affected rows on success, and -1 if the last query failed.
         * @see getNumRows()
         **/
        public function getAffectedRows($connect_id = NULL);
        /**
         * @brief Get number of rows in result
         * @param $query_id The query, If it was not specified, the current query is assumed
         * @return The number of rows in a result set on success, or FALSE on failure
         * @see getAffectedRows()
         **/
        public function getNumRows($query_id = NULL);
        /**
         * @brief Get server information
         * @param $info_name information names, separated with comma. If it was not provided, all information would be returned.
         * @param $connect_id The MySQL connection. If it was not specified, the current connection is assumed
         * @return Return a array including all selected server informations
         **/
        public function getServerInfo($info_name = NULL, $connect_id = NULL);
        /**
         * @brief Get current system status
         * @param $connect_id The MySQL connection. If it was not specified, the current connection is assumed
         * @return return a string including uptime, threads, queries, open tables, flush tables and queries per second, else return NULL
         **/
        public function getServerStatus($connect_id = NULL);
        /**
         * @brief Send an SQL query to MySQL, without fetching and buffering the result rows
         * @param $query_string A SQL query
         * @param $connect_id The MySQL connection. If it was not specified, the current connection is assumed
         * @return For SELECT, SHOW, DESCRIBE or EXPLAIN statements, it returns a resource on success, or FALSE on error.<br />For other type of SQL statements, UPDATE, DELETE, DROP, etc, it returns TRUE on success or FALSE on error.
         **/
        public function unbufferedQuery($query_string, $connect_id = NULL);
        /**
         * @brief Returns the text of the error message from previous MySQL operation
         * @param $connect_id The MySQL connection. If it was not specified, the current connection is assumed
         * @return Returns the error text from the last MySQL function, or '' (empty string) if no error occurred.
         **/
        public function getErrorMessage($connect_id = NULL);
        /**
         * @brief Returns the numerical value of the error message from previous MySQL operation
         * @param $connect_id The MySQL connection. If it was not specified, the current connection is assumed
         * @return Returns the error number from the last MySQL function, or 0 (zero) if no error occurred.
         **/
        public function getErrorNumber($connect_id = NULL);
        /**
         * @brief Set configure for database
         * @param $config_name Configure name. If it was a array, configure pair is assumed
         * @param $config_value Configure value. If $config_name was a array, it would be ignored
         * @return If one of provided configure names was valid, return TRUE, else return FALSE
         **/
        public function setConfig($config_name, $config_value = NULL);
        /**
         * @brief Get configure for database
         * @param $config_name List of configure names separated with comma. If it was not provided, all configure would be returned.
         * @return Return a array including all selected configure, and index was configure name, value was configure value. If one configure name was provided, the configure value would be return.
         **/
        public function getConfig($config_name = NULL);
}
?>

作者: cfeeling   发布时间: 2007-05-27

mysqli实现类
复制内容到剪贴板
代码:
<?php
/**
* @brief Operating Database (MySQL Improved)
* @author feeling <[email][email protected][/email]>
* @version 1.0
* @par Config Index List:
* \arg \c host host name or IP address of the database server
* \arg \c user User name for login into the database server
* \arg \c password User's password for login into the database server
* \arg \c dbname The default database name
* \arg \c prefix prefix for all tables in the database
* \arg \c socket SOCKET for connecting to the database(Linux/Unix)
* \arg \c port port of the database server
* \arg \c persistent Whether using a persistent connection
**/
class ImMySQL implements IDatabase
{
        private $config;        /**< Configure for the database server */
        const VERSION = '1.0';        /**< Script version */
        private $connect_id = FALSE;        /**< The current connection to database server */
        private $query_id = NULL;        /**< The current query */
        private $records = array();        /**< Result of SQL query */
        public $error_messages = array();        /**< Error stack */

        function __construct()
        {
                $this->config = array(
                        'host'         => 'localhost',
                        'user'         => 'root',
                        'password'        => '',
                        'dbname'        => '',
                        'prefix'                => '',
                        'socket'                => '/tmp/mysql.sock',
                        'port'                        => 3306
                );
        }

        public function connect()
        {
                if (TRUE == empty($this->config['password'])) $this->config['password'] = NULL;
                $this->connect_id = @new mysqli($this->config['host'], $this->config['user'], $this->config['password'], $this->config['dbname'], $this->config['port'], $this->config['socket']);
                if (FALSE == $this->connect_id) $this->error_messages[] = array('code' => mysqli_connect_errno(), 'file' => __FILE__, 'line' => __LINE__);
                return $this->connect_id;
        }

        public function close($connect_id = NULL)
        {
                if (TRUE == empty($connect_id)) $connect_id = & $this->connect_id;
                if (TRUE == @is_resource($connect_id)) return $connect_id->close();
                return FALSE;
        }

        public function query($query_string, $connect_id = NULL)
        {
                if (NULL == $connect_id) $connect_id = &$this->connect_id;
                if (FALSE == empty($connect_id))
                {
                        $this->query_id = $connect_id->query($query_string);
                        if (FALSE == $this->query_id) $this->error_messages[] = array('code' => $this->getErrorMessage($connect_id), 'file' => __FILE__, 'line' => __LINE__);
                        return $this->query_id;
                }
                return FALSE;
        }

        public function escape($query_string, $connect_id = NULL)
        {
                if (NULL == $connect_id) $connect_id = &$this->connect_id;
                if (FALSE == empty($connect_id))
                {
                        return $connect_id->real_escape_string($query_string);
                }
                return '';
        }

        public function freeResult($query_id = NULL)
        {
                if (NULL == $query_id) $query_id = & $this->query_id;
                if (TRUE == @is_object($query_id) && $query_id->free_result())
                {
                        $this->records = array();
                        return TRUE;
                }
                return FALSE;
        }

        public function fetchArray($query_type = 'BOTH', $query_id = NULL)
        {
                if (NULL == $query_id) $query_id = & $this->query_id;
                if (FALSE == empty($query_id))
                {
                        switch ($query_type)
                        {
                                case 'NUM': $query_type = MYSQL_NUM; break;
                                case 'ASSOC': $query_type = MYSQLI_ASSOC; break;
                                default: $query_type = MYSQLI_BOTH; break;
                        }
                        $tmp = $query_id->fetch_array($query_type);
                        if (NULL != $tmp)
                        {
                                $this->records[] = $tmp;
                                return $tmp;
                        }
                }
                return FALSE;
        }

        public function fetchArrayBat($query_type = 'BOTH', $query_id = NULL)
        {
                if (NULL == $query_id) $query_id = & $this->query_id;
                if (FALSE == empty($query_id))
                {
                        switch ($query_type)
                        {
                                case 'NUM': $query_type = MYSQL_NUM; break;
                                case 'ASSOC': $query_type = MYSQLI_ASSOC; break;
                                default: $query_type = MYSQLI_BOTH; break;
                        }
                        $result = array();
                        while (TRUE == ($tmp = $query_id->fetch_array($query_type))) $result[] = $tmp;
                        if (0 < count($result))
                        {
                                $this->records = $result;
                                return $result;
                        }
                }
                return FALSE;
        }

        public function getInsertId($connect_id = NULL)
        {
                if (NULL == $connect_id) $connect_id = & $this->connect_id;
                if (FALSE == empty($connect_id)) $insert_id = $connect_id->insert_id;
                return FALSE;
        }

        public function getAffectedRows($connect_id = NULL)
        {
                if (NULL == $connect_id) $connect_id = & $this->connect_id;
                if (FALSE == empty($connect_id)) return $connect_id->affected_rows;
                return FALSE;
        }

        public function getNumRows($query_id = NULL)
        {
                if (NULL == $query_id) $query_id = & $this->query_id;
                if (FALSE == empty($query_id)) return $query_id->num_rows;
                return FALSE;
        }

        public function getServerInfo($info_name = NULL, $connect_id = NULL)
        {
                $server_info = array();
                if (NULL == $connect_id) $connect_id = & $this->connect_id;
                $valid_info_names = array('version', 'protocol', 'connection', 'cversion', 'charset');
                if (TRUE == empty($info_name)) $info_names = $valid_info_names;
                else
                {
                        $tmp = explode(',', $info_name);
                        for ($i = 0; $i < count($tmp); $i++)
                        {
                                if (TRUE == in_array(trim($tmp[$i]), $valid_info_names)) $info_names[] = trim($tmp[$i]);
                        }
                }
                for ($i = 0; $i < count($info_names); $i++)
                {
                        switch ($info_names[$i])
                        {
                                case 'version': $tmp = $connect_id->server_version; break;
                                case 'protocol': $tmp = $connect_id->protocol_version; break;
                                case 'connection': $tmp = $connect_id->host_info; break;
                                case 'cversion': $tmp = mysqli_get_client_version(); break;
                                case 'charset': $tmp = $connect_id->character_set_name(); break;
                        }
                        $server_info[$info_names[$i]] = $tmp;
                }
                return $server_info;
        }

        public function getServerStatus($connect_id = NULL)
        {
                if (NULL == $connect_id) $connect_id = & $this->connect_id;
                $stat_string = $connect_id->stat();        // Like as Uptime: 272  Threads: 1  Questions: 5340  Slow queries: 0 Opens: 13  Flush tables: 1  Open tables: 0  Queries per second avg: 19.632 Memory in use: 8496K  Max memory used: 8560K
                $matched = array();
                preg_match('/Uptime:\s*(\d+)\s*Threads:\s*(\d+)\s*Questions:\s*(\d+)\s*Slow queries:\s*(\d+)\s*Opens:\s*(\d+)\s*Flush tables:\s*(\d+)\s*Open tables:\s*(\d+)\s*Queries per second avg:\s*([\.\d]+)\s*Memory in use:\s*([\w\d]+)\s*Max memory used:\s*([\w\d]+)\s*/is', $stat_string, $matched);
                $status = array(
                        'uptime'        => $matched[1],        // Uptime
                        'threads'         => $matched[2],        // Threads
                        'questions'        => $matched[3],        // Questions
                        'queries'         => $matched[4],        // Slow queries
                        'opens'        => $matched[5],        // Opens
                        'ftables'        => $matched[6],        // Flush tables
                        'otables'         => $matched[7],        // Open tables
                        'qpsa'         => $matched[8],        // Queries per second avg
                        'memused'        => $matched[9],        // Memory in use
                        'maxmem'        => $matched[10]        // Max memory used
                );
                return $status;
        }

        public function unbufferedQuery($query_string, $connect_id = NULL)
        {
                if (NULL == $connect_id) $connect_id = & $this->connect_id;
                if (FALSE == empty($connect_id)) return $connect_id->real_query($query_string);
                return FALSE;
        }

        public function getErrorMessage($connect_id = NULL)
        {
                if (NULL == $connect_id) $connect_id = & $this->connect_id;
                if (FALSE == empty($connect_id)) return $connect_id->error;
                return '';
        }

        public function getErrorNumber($connect_id = NULL)
        {
                if (NULL == $connect_id) $connect_id = & $this->connect_id;
                if (FALSE == empty($connect_id)) return $connect_id->errno;
                return 0;
        }

        public function setConfig($config_name, $config_value = NULL)
        {
                if (FALSE == is_array($config_name))
                {
                        if (TRUE == array_key_exists($config_name, $this->config))
                        {
                                $this->config[$config_name] = $config_value;
                                return TRUE;
                        }
                        return FALSE;
                }
                else
                {
                        $found = FALSE;
                        foreach ($config_name as $key => $value)
                        {
                                if (TRUE == array_key_exists($key, $this->config))
                                {
                                        $found = TRUE;
                                        $this->config[$key] = $value;
                                }
                        }
                        return $found;
                }
        }

        public function getConfig($config_name = NULL)
        {
                $config_values = array();
                $config_names = explode(',', $config_name);
                for ($i = 0; $i < count($config_names); $i++)
                {
                        if (TRUE == array_key_exists(trim($config_names[$i]), $this->config)) $config_values[$config_names[$i]] = $this->config[$config_names[$i]];
                }
                if (2 > count($config_names) && 0 < count($config_values))
                {
                        reset($config_values);
                        return current($config_values);
                }
                else return $config_values;
        }
}
?>

作者: cfeeling   发布时间: 2007-05-27

MySQL的实现,for php4
复制内容到剪贴板
代码:
<?php
/**
* @brief Operating Database (MySQL)
* @author feeling <[email][email protected][/email]>
* @date 2007-5-26 13:45
* @version 1.0
* @warning This class was only for PHP4, If you used PHP5, please select ImMySQL class
* @par Config Index List:
* @arg @c host host name or IP address of the database server
* @arg @c user User name for login into the database server
* @arg @c password User's password for login into the database server
* @arg @c dbname The default database name
* @arg @c prefix prefix for all tables in the database
* @arg @c socket SOCKET for connecting to the database(Linux/Unix)
* @arg @c port port of the database server
* @arg @c persistent Whether using a persistent connection
**/
class MySQL4
{
        var $config = array();        /**< Configure for the database server */
        var $VERSION = '1.0';        /**< Script version */
        var $connect_id = FALSE;        /**< The current connection to database server */
        var $query_id = NULL;        /**< The current query */
        var $records = array();        /**< Result of SQL query */
        var $error_messages = array();        /**< Error stack */

        function MySQL4()
        {
                $this->config = array(
                        'host'         => 'localhost',
                        'user'         => 'root',
                        'password'        => '',
                        'dbname'        => '',
                        'prefix'                => '',
                        'socket'                => '/tmp/mysql.sock',
                        'port'                        => 3306,
                        'persistent'        => FALSE
                );
        }

        function connect()
        {
                $fun_connect = ((TRUE == $this->config['persistent']) ? 'mysql_pconnect' : 'mysql_connect');
                if (TRUE == empty($this->config['password'])) $this->connect_id = @$fun_connect($this->config['host'], $this->config['user']);
                else $this->connect_id = @$fun_connect($this->config['host'], $this->config['user'], $this->config['password']);
                if (FALSE == $this->connect_id) $this->error_messages[] = array('code' => mysql_errno(), 'file' => __FILE__, 'line' => __LINE__);
                elseif (FALSE == empty($this->config['dbname'])) @mysql_select_db($this->config['dbname'], $this->connect_id);
                return $this->connect_id;
        }

        function close($connect_id = NULL)
        {
                if (FALSE == @is_resource($connect_id)) $connect_id = & $this->connect_id;
                if (FALSE != $this->connect_id && FALSE == $this->config['persistent']) return @mysql_close($connect_id);
                return (TRUE == $this->config['persistent'] || FALSE);
        }

        function query($query_string, $connect_id = NULL)
        {
                if (FALSE == @is_resource($connect_id)) $connect_id = & $this->connect_id;
                if (TRUE == @is_resource($connect_id))
                {
                        if (FALSE == ($this->query_id = mysql_query($query_string, $connect_id))) $this->error_messages[] = array('code' => mysql_errno(), 'file' => __FILE__, 'line' => __LINE__);
                        return $this->query_id;
                }
                return FALSE;
        }

        function escape($query_string, $connect_id = NULL)
        {
                if (NULL == $connect_id) $connect_id = &$this->connect_id;
                if (FALSE == empty($connect_id))
                {
                        return @mysql_real_escape_string($query_string, $connect_id);
                }
                return '';
        }

        function freeResult($query_id = NULL)
        {
                if (TRUE == empty($query_id)) $query_id = & $this->query_id;
                if (TRUE == @is_resource($query_id))
                {
                        if (FALSE == @mysql_free_result($query_id)) $this->error_messages[] = array('code' => mysql_errno(), 'file' => __FILE__, 'line' => __LINE__);
                        else return TRUE;
                }
                return FALSE;
        }

        function fetchArray($query_type = 'BOTH', $query_id = NULL)
        {
                if (TRUE == empty($query_id)) $query_id = & $this->query_id;
                if (TRUE == @is_resource($query_id))
                {
                        switch ($query_type)
                        {
                                case 'NUM': $type = MYSQL_NUM; break;
                                case 'ASSOC': $type = MYSQL_ASSOC; break;
                                default: $type = MYSQL_BOTH; break;
                        }
                        $result = @mysql_fetch_array($query_id, $type);
                        if (FALSE == $result) $this->error_messages[] = array('code' => mysql_errno(), 'file' => __FILE__, 'line' => __LINE__);
                        else $this->records[] = $result;
                }
                return $result;
        }

        function fetchArrayBat($query_type = 'BOTH', $query_id = NULL)
        {
                if (TRUE == empty($query_id)) $query_id = & $this->query_id;
                if (TRUE == @is_resource($query_id))
                {
                        switch ($query_type)
                        {
                                case 'NUM': $type = MYSQL_NUM; break;
                                case 'ASSOC': $type = MYSQL_ASSOC; break;
                                default: $type = MYSQL_BOTH; break;
                        }
                        while (TRUE == ($tmp = @mysql_fetch_array($query_id, $type))) $this->records[] = $tmp;
                }
                return $this->records;
        }

        function getInsertId($connect_id = NULL)
        {
                if (TRUE == empty($connect_id)) $connect_id = & $this->connect_id;
                if (TRUE == @is_resource($connect_id)) return @mysql_insert_id($connect_id);
                return FALSE;
        }

        function getAffectedRows($connect_id = NULL)
        {
                if (TRUE == empty($connect_id)) $connect_id = & $this->connect_id;
                if (TRUE == @is_resource($connect_id)) return @mysql_affected_rows($connect_id);
                return FALSE;
        }

        function getNumRows($query_id = NULL)
        {
                if (TRUE == empty($query_id)) $query_id = & $this->query_id;
                if (TRUE == @is_resource($query_id)) return @mysql_num_rows($query_id);
                return FALSE;
        }

        function getServerInfo($info_name = NULL, $connect_id = NULL)
        {
                $server_info = array();
                if (NULL == $connect_id) $connect_id = & $this->connect_id;
                $valid_info_names = array('version', 'protocol', 'connection', 'cversion', 'charset');
                if (TRUE == empty($info_name)) $info_names = $valid_info_names;
                else
                {
                        $tmp = explode(',', $info_name);
                        for ($i = 0; $i < count($tmp); $i++)
                        {
                                if (TRUE == in_array(trim($tmp[$i]), $valid_info_names)) $info_names[] = trim($tmp[$i]);
                        }
                }
                for ($i = 0; $i < count($info_names); $i++)
                {
                        switch ($info_names[$i])
                        {
                                case 'version':
                                        $matched = array();
                                        $tmp = @mysql_get_server_info($connect_id);
                                        preg_match('/^(\d+)\.(\d+)\.(\d+).*/i', $tmp, $matched);
                                        $tmp = $matched[1] * 10000 + $matched[2] * 100 + $matched[3];
                                        break;
                                case 'protocol': $tmp = @mysql_get_proto_info($connect_id); break;
                                case 'connection': $tmp = @mysql_get_host_info($connect_id); break;
                                case 'cversion':
                                        $matched = array();
                                        $tmp = @mysql_get_client_info();
                                        preg_match('/^(\d+)\.(\d+)\.(\d+).*/i', $tmp, $matched);
                                        $tmp = $matched[1] * 10000 + $matched[2] * 100 + $matched[3];
                                        break;
                                case 'charset': $tmp = @mysql_client_encoding($connect_id); break;
                        }
                        $server_info[$info_names[$i]] = $tmp;
                }
                return $server_info;
        }

        function getServerStatus($connect_id = NULL)
        {
                if (NULL == $connect_id) $connect_id = & $this->connect_id;
                $stat_string = @mysql_stat($connect_id);        // Like as Uptime: 272  Threads: 1  Questions: 5340  Slow queries: 0 Opens: 13  Flush tables: 1  Open tables: 0  Queries per second avg: 19.632
                $matched = array();
                preg_match('/Uptime:\s*(\d+)\s*Threads:\s*(\d+)\s*Questions:\s*(\d+)\s*Slow queries:\s*(\d+)\s*Opens:\s*(\d+)\s*Flush tables:\s*(\d+)\s*Open tables:\s*(\d+)\s*Queries per second avg:\s*([\.\d]+)\s*/is', $stat_string, $matched);
                $status = array(
                        'uptime'        => $matched[1],        // Uptime
                        'threads'         => $matched[2],        // Threads
                        'questions'        => $matched[3],        // Questions
                        'queries'         => $matched[4],        // Slow queries
                        'opens'        => $matched[5],        // Opens
                        'ftables'        => $matched[6],        // Flush tables
                        'otables'         => $matched[7],        // Open tables
                        'qpsa'         => $matched[8],        // Queries per second avg
                        'memused'        => 0,        // Memory in use
                        'maxmem'        => 0        // Max memory used
                );
                return $status;
        }

        function unbufferedQuery($query_string, $connect_id = NULL)
        {
                if (NULL == $connect_id) $connect_id = & $this->connect_id;
                if (FALSE == empty($connect_id))
                {
                        $result = @mysql_unbuffered_query($query_string, $connect_id);
                        return $result;
                }
                return FALSE;
        }

        function getErrorMessage($connect_id = NULL)
        {
                if (NULL == $connect_id) $connect_id = & $this->connect_id;
                if (FALSE == empty($connect_id)) return @mysql_error($connect_id);
                return '';
        }

        function getErrorNumber($connect_id = NULL)
        {
                if (NULL == $connect_id) $connect_id = & $this->connect_id;
                if (FALSE == empty($connect_id)) return @mysql_errno($connect_id);
                return 0;
        }

        function setConfig($config_name, $config_value = NULL)
        {
                if (FALSE == is_array($config_name))
                {
                        if (TRUE == array_key_exists($config_name, $this->config))
                        {
                                $this->config[$config_name] = $config_value;
                                return TRUE;
                        }
                        return FALSE;
                }
                else
                {
                        $found = FALSE;
                        foreach ($config_name as $key => $value)
                        {
                                if (TRUE == array_key_exists($key, $this->config))
                                {
                                        $found = TRUE;
                                        $this->config[$key] = $value;
                                }
                        }
                        return $found;
                }
        }

        function getConfig($config_name = NULL)
        {
                $config_values = array();
                $config_names = explode(',', $config_name);
                for ($i = 0; $i < count($config_names); $i++)
                {
                        if (TRUE == array_key_exists(trim($config_names[$i]), $this->config)) $config_values[$config_names[$i]] = $this->config[$config_names[$i]];
                }
                if (2 > count($config_names) && 0 < count($config_values))
                {
                        reset($config_values);
                        return current($config_values);
                }
                else return $config_values;
        }
}
?>

作者: cfeeling   发布时间: 2007-05-27

欢迎批评指导!
后面两个class因为篇幅问题去掉了注释。
使用:
复制内容到剪贴板
代码:
$db_config = array(
    'host' => 'localhost',
    'user' => 'root',
    'password' => '',
    'dbname' => 'test',
    'prefix' => '',
    'socket' => '/tmp/mysql.sock',
    'port' => 3306,
    'persistent' => FALSE
);
$dbop = Database::getInstance('mysqli', $db_config);
$sql_query = "select * from " . $dbop->getConfig('prefix') . "test_table";
$dbop->query($sql_query);
// 获取第一条记录
$records = $dbop->fetchArray(NULL, 'ASSOC');
// 获取所有记录
$records = $dbop->fetchArrayBat(NULL, 'ASSOC');
$dbop->freeResult();
$dbop->close();

作者: cfeeling   发布时间: 2007-05-27

能否问一下,你的是用单件设计模式吗????????

新手不明白!!谢谢能解答!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!等!!!!!!!!!!!!!!

作者: pp987456123   发布时间: 2007-05-27

引用:
原帖由 pp987456123 于 2007-5-27 17:36 发表
能否问一下,你的是用单件设计模式吗????????

新手不明白!!谢谢能解答!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!等!!!!!!!!!!!!!!
对的,它就是单件设计模式,使用它的目的就是尽量减少新建数据库连接,以达到减少占用系统资源的目的
在设计模型中叫 Singleton

[ 本帖最后由 cfeeling 于 2007-5-27 22:34 编辑 ]

作者: cfeeling   发布时间: 2007-05-27

单件设计模式是什么,讷能够介绍一下吗

作者: sanler   发布时间: 2007-05-27

参考 http://www.linuxdby.com/html/program/aspnet/20070428/25759.html

Singleton模式
按照设计模式中的定义,Singleton模式的用途是“ensure a class has only one instance, and provide a global point of access to it(确保每个类只有一个实例,并提供它的全局访问点)”。


它可以解决什么问题,或者换句话说,我们使用它的动机是什么?几乎在每个应用程序中,都需要有一个从中进行全局访问和维护某种类型数据的区域。在面向对象的(OO)系统中也有这种情况,在此类系统中,在任何给定时间只应运行一个类或某个类的一组预定义数量的实例。例如,当使用某个类来维护增量计数器时,此简单的计数器类需要跟踪在多个应用程序领域中使用的整数值。此类需要能够增加该计数器并返回当前的值。对于这种情况,所需的类行为应该仅使用一个类实例来维护该整数,而不是使用其它类实例来维护该整数。
最初,人们可能会试图将计数器类实例只作为静态全局变量来创建。这是一种通用的方法,但实际上只解决一部分问题;它解决了全局可访问性问题,但没有采取任何措施来确保在任何给定的时间只运行一个类实例。应该由类本身来负责只使用一个类实例,而不是由类用户来负责。应该始终不要让类用户来监视和控制运行的类实例的数量。
所需要的是使用某种方法来控制如何创建类实例,然后确保在任何给定的时间只创建一个类实例。这会确切地给我们提供所需的行为,并使客户端不必了解任何类细节。

逻辑模型
Singleton模型非常简单直观。(通常)只有一个Singleton实例。客户端通过一个已知的访问点来访问Singleton实例。在这种情况下,客户端是一个需要访问唯一Singleton实例的对象。图1以图形方式显示此关系。
物理模型
Singleton模式的物理模型也是非常简单的。但是,随着时间的推移,实现Singleton的方式也略有不同。让我们看一下原始的GoFSingleton实现。图2显示按设计模式所定义的原始Singleton模式的UML模型。
我们看到的是一个简单的类图表,显示有一个Singleton对象的私有静态属性以及返回此相同属性的公共方法Instance()。这实际上是Singleton的核心。还有其他一些属性和方法,用于说明在该类上允许执行的其他操作。为了便于此次讨论,让我们将重点放在实例属性和方法上。
客户端仅通过实例方法来访问任何Singleton实例。此处没有定义创建实例的方式。我们还希望能够控制如何以及何时创建实例。在OO开发中,通常可以在类的构造函数中最好地处理特殊对象的创建行为。这种情况也不例外。我们可以做的是,定义我们何时以及如何构造类实例,然后禁止任何客户端直接调用该构造函数。这是在Singleton构造中始终使用的方法。让我们看一下设计模式中的原始示例。通常,将下面所示的C++Singleton示例实现代码示例视为Singleton的默认实现。本示例已移植到很多其他编程语言中,通常它在任何地方的形式与此几乎相同。

作者: cfeeling   发布时间: 2007-05-27

还有这篇文章 http://www.linuxmine.com/48645.html

作者: cfeeling   发布时间: 2007-05-27

长见识了,看来自己还得好好学
你那个类库应该可以直接放到一个文件中调用吧

作者: sanler   发布时间: 2007-05-28

不用也要支持

作者: welefen   发布时间: 2007-05-28

引用:
原帖由 sanler 于 2007-5-28 09:48 发表
长见识了,看来自己还得好好学
你那个类库应该可以直接放到一个文件中调用吧
用法在5楼有了,5楼只是没有加入 require_once 语句

因为在 php5 中有一个 __autoload 的magic method,所以我一般都不用require或者include了

作者: cfeeling   发布时间: 2007-05-28

加入高亮度嘛!这样黑乎乎的很难看!

作者: 蓝魔1982   发布时间: 2007-06-06

没有调试出来
Fatal error: Call to undefined method Database::getConfig()

作者: 阳垭   发布时间: 2007-06-21

搞一个类似与MySQLi的类啊!

作者: azone   发布时间: 2007-06-21