2009年1月5日 星期一

php與MySQL連接類別

日前整理的一個類別, 特殊的地方在於使用了Array儲存查詢結果, 所以能夠依照查詢時給予的ID重新調用結果。
此外設定檔存放在db_mysql.inc中, 如果臨時需要調換資料庫則在建構子中填入即可。

db_mysql.inc :

<?php

// or set date.timezone = Asia/Taipei in php.ini
if(function_exists("date_default_timezone_set")) date_default_timezone_set('Asia/Taipei');

// database configure.
define(DB_HOST, 'localhost');
define(DB_USER, 'root');
define(DB_PASSWD, 'root1234');
define(DB_DATABASE, 'PHP_MODULE_TEST');
define(DB_PERSISTENT, false);
define(DB_UTF, true);

?>

database_mysql.php :


<?php

require('db_mysql.inc');

class DataBase 
{
    // Connection parameters
    var $host = '';
    var $user = '';
    var $password = '';
    var $database = '';
    var $persistent = false;
    var $utf = true;

    // Database connection handle
    var $conn = null;
    var $connected = false;
 
    // Query result
    var $result = array();
    var $insert_id = array();
    
    // constructor.
    function DataBase($otherDatabase = null)
    {
        $this->host = DB_HOST;
        $this->user = DB_USER;
        $this->password = DB_PASSWD;
        if($otherDatabase == null)
            $this->database = DB_DATABASE;
        else
            $this->database = $otherDatabase;
        $this->persistent = DB_PERSISTENT;
        $this->utf = DB_UTF;
    }

    // open database connection.
    function connect() 
    {
        // Choose the appropriate connect function
        if ($this->persistent){
            $func = 'mysql_pconnect';
        }else{
            $func = 'mysql_connect';
        }
     
        // Connect to the MySQL server
        $this->conn = $func($this->host, $this->user, $this->password) or die($this->error());
        if($this->utf == true){
            mysql_query("SET NAMES 'utf8'");
        }

        // Select the requested database
        mysql_select_db($this->database, $this->conn) or die($this->error());

        $this->connected = true;
    }

    // database query.
    function query($rs_id='RESULT_ID', $sql='', $debug=0)
    {
        if($this->connected == false) $this->connect();
        if($debug!=0) $this->debug($sql, $debug);
        $this->result[$rs_id] = mysql_query($sql, $this->conn) or die($this->error());
        $this->insert_id[$rs_id] = mysql_insert_id();
        return ($this->result[$rs_id] != false);
    }
    
    // 取得先前操作MySQL所受到影響的列的數目
    function affectedRows()
    {
        return (mysql_affected_rows($this->conn));
    }

    // 取得結果中列的數目
    function numRows($rs_id)
    {
        return (mysql_num_rows($this->result[$rs_id]));
    }
    
    // 取得查詢後的物件結果(使用$row->user_id查詢)
    function fetchObject($rs_id)
    {
        return (mysql_fetch_object($this->result[$rs_id]));
    }
    
    // 取得查詢後的陣列結果(使用$row['user_id']查詢)
    function fetchArray($rs_id)
    {
        return (mysql_fetch_array($this->result[$rs_id]));
    }
    
    // 回傳一個欄位的值(ex: select name from school where id=1, 傳回$rs['name'])
    function fetchAssoc($rs_id)
    {
        return (mysql_fetch_assoc($this->result[$rs_id]));
    }

    // 釋放�憶體
    function freeResult($rs_id)
    {
        return (mysql_free_result($this->result[$rs_id]));
    }

    // 移動內部指標
    function resetResult($rs_id)
    {
        return (mysql_data_seek($this->result[$rs_id], 0));
    }
    
    // 取得先前insert操作的id主鍵(AUTO_INCREMENTED)
    function getInsertID($rs_id)
    {
        return $this->insert_id[$rs_id];
    }

    // show database configure.
    function showDetail()
    {
        $str = '';
        $str .= 'DB_HOST: '.DB_HOST.'<br>';
        $str .= 'DB_USER: '.DB_USER.'<br>';
        $str .= 'DB_PASSWD: '.DB_PASSWD.'<br>';
        $str .= 'DB_DATABASE: '.DB_DATABASE.'<br>';
        if(DB_PERSISTENT == true)
            $str .= 'DB_PERSISTENT: true<br>';
        else
            $str .= 'DB_PERSISTENT: false<br>';
        if(DB_UTF == true)
            $str .= 'DB_UTF: true<p>';
        else
            $str .= 'DB_UTF: false<p>';

        return $str;
    }

    // debug sql condition.
    function debug($sql,$debug)
    {
        if($debug==1)echo "<script>alert(\"".$sql."\");</script>";
        else if($debug==2)echo '<p><b>'.$sql.'</b></p>';
        else if($debug==3)exit;
    }                                 

    // close connection. (無法關閉pconnect所開啟的連線)
    function close()
    {
        $this->connected = false;
        return mysql_close($this->conn);
    }

    function error()
    {
        return mysql_error();
    }
}
?>

2 則留言:

  1. 用PDO比較方便哦~

    回覆刪除
  2. 嗯...沒錯, PDO(php data object)一個就能打天下, 而且php6以後強制改為使用pdo作為連接中介, 也就是說以前的東西都不能用啦!這年頭大家都來完這招...不過這麼作也可能導致一堆人不更新。

    回覆刪除