首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

MySQL 資料庫操作類(v1127):支援連線池、除錯模式、完整 CRUD 封裝

     編輯:PHP 綜合知識

類別特色

  • 支援一般連線(mysql_connect)與持久連線(mysql_pconnect)
  • 內建除錯開關($debug),輸出 SQL 與錯誤資訊
  • 封裝 query、fetch_array/assoc/row/object、num_rows、insert_id、affected_rows
  • 提供 show_tables、show_dbs、create_db、drop_db、drop_table 等管理功能
  • 自動釋放結果集記憶體(free_result)

核心程式碼結構

class Mysql {
    private $db_host, $db_user, $db_pass, $db_name, $db_charset, $conn;
    public $debug = false;
    private $query_id, $result, $num_rows, $insert_id;

    function __construct($host, $user, $pass, $name, $charset, $conn_type) {
        $this->db_host = $host; $this->db_user = $user; $this->db_pass = $pass;
        $this->db_name = $name; $this->db_charset = $charset; $this->conn = $conn_type;
        $this->connect();
    }
    function __destruct() { @mysql_close($this->conn); }

    public function connect() {
        $this->conn = ($this->conn == 'pconn') 
            ? @mysql_pconnect($this->db_host, $this->db_user, $this->db_pass)
            : @mysql_connect($this->db_host, $this->db_user, $this->db_pass);
        if (!$this->conn) $this->show_error('連線失敗');
        @mysql_select_db($this->db_name, $this->conn) or $this->show_error("資料庫 {$this->db_name} 不可用");
        mysql_query("SET NAMES {$this->db_charset}");
        return $this->conn;
    }

    public function query($sql) {
        if ($this->query_id) $this->free_result();
        $this->query_id = @mysql_query($sql, $this->conn);
        if (!$this->query_id) $this->show_error("SQL 執行錯誤: $sql");
        return $this->query_id;
    }

    public function fetch_array() { return $this->query_id ? mysql_fetch_array($this->query_id) : null; }
    public function fetch_assoc() { return $this->query_id ? mysql_fetch_assoc($this->query_id) : null; }
    public function fetch_row()   { return $this->query_id ? mysql_fetch_row($this->query_id) : null; }
    public function fetch_object(){ return $this->query_id ? mysql_fetch_object($this->query_id) : null; }

    public function num_rows() { return $this->query_id ? mysql_num_rows($this->query_id) : 0; }
    public function insert_id(){ return mysql_insert_id(); }
    public function free_result() { @mysql_free_result($this->query_id); $this->query_id = 0; }

    public function show_error($msg) {
        if ($this->debug) echo "錯誤:$msg
返回:".mysql_error()."

"; else echo "

出現錯誤!

"; } // ... show_tables, show_dbs, create_db, drop_db, drop_table, get_info 等管理方法 }

使用範例

$db = new Mysql('localhost', 'root', 'pwd', 'testdb', 'utf8', 'conn'); // 或 'pconn'
$db->debug = true;  // 開啟除錯
$db->query("SELECT * FROM users WHERE id > 10");
while ($row = $db->fetch_assoc()) {
    print_r($row);
}
$db->free_result();

遷移提醒

同前一篇,基於已移除的 mysql_* 擴充套件。新專案請使用 mysqli 或 PDO 重寫,並善用預備語句防止 SQL 注入。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved