PHP mysql 5.0용 DB class (자동오류 저장지원) > php

본문 바로가기
사이트 내 전체검색

php

PHP mysql 5.0용 DB class (자동오류 저장지원)

페이지 정보

작성자 서방님 댓글 0건 조회 117회 작성일 13-03-07 08:45

본문

<?
class dbconn {
    protected $user;
    protected $pass;
    protected $dbhost;
    protected $dbname;
    protected $conn; // Database connection handle.
    protected $exception;
   
    //public function __construct($user, $pass, $dbhost, $dbname, $exception = "MysqlException") {
 public function __construct($dbset,$exception="MysqlException") {
        $this->user = $dbset[user];
        $this->pass = $dbset[pass];
        $this->dbhost = $dbset[dbhost];
        $this->dbname = $dbset[dbname];
        $this->exception = $exception;
    }
    
    protected function connect() {
        $this->conn = mysql_connect($this->dbhost, $this->user, $this->pass);
        if(!is_resource($this->conn)) {
            throw new $this->exception("Error establishing a database connection");
        }
        if(!mysql_select_db($this->dbname, $this->conn)) {
            throw new $this->exception("Can’t select database, Please check DB, username, password.");
        }
    }

 public function close()
 {
        if(!$this->conn) return false;
  if($this->conn) @mysql_close($this->conn);
  $this->conn = false;
  return true;
 }
   
    public function execute($query) {
        try {
            if(!$this->conn) {
                $this->connect();
            }     
            $ret = mysql_query($query, $this->conn);
            if(!$ret) {
    throw new $this->exception;
            }
            if(!is_resource($ret)) {
                return true;
            }
            else {
                $stmt = new dbconnStatement($this->conn, $query, $this->exception);
                $stmt->result = $ret;
                return $stmt;
            }
        } catch (MysqlException $e) {
   $e->displayError();
            exit;
        }
    }
    
    public function prepare($query) {
        try {
            if(!$this->conn) {
                $this->connect();
            }
            return new dbconnStatement($this->conn, $query, $this->exception);
        } catch (MysqlException $e) {
            $e->displayError();
            exit;
        }
        
    }
};

// Wrapper for mysql return value resource,
// resource will be returned back to the dbconn.
class dbconnStatement {
    public    $affected_rows;
    public    $result;
    public    $binds;
    public    $query;
    public    $retval;
    protected $conn;    
    protected $exception;
    
    public function __construct($conn, $query, $exception) {
        $this->query = $query;
        $this->conn  = $conn;
        $this->exception = $exception;
        if(!is_resource($conn)) {
            throw new $this->exception("Not a valid database connection");
        }
    }
    
    // A bit faster.
    public function fetch_row() {
        if(!$this->result) {
            throw new $this->exception("Query not executed");
        }
        return mysql_fetch_row($this->result);
    }
    
    private function fetch_obj() {
        if(!$this->result) {
            throw new $this->exception("Query not executed");
        }
        return mysql_fetch_object($this->result);
    }
    
    private function fetch_array() {
        if(!$this->result) {
            throw new $this->exception("Query not executed");
        }
        return mysql_fetch_array($this->result, MYSQL_ASSOC);     
    }
    
    // Fetch all.
    private function fetchall_array() {
        while($row = $this->fetch_array()) {
            $this->retval[] = $row;
        }
        return $this->retval;
    }
    
    private function fetchall_obj() {
        while($row = $this->fetch_obj()) {
            $this->retval[] = $row;
        }
        return $this->retval;
    }
    
    public function execute() {
        try {
            $this->_flush();
            $binds = func_get_args();
            foreach($binds as $index => $name) {
                $this->binds[$index+1] = $name;
            }
            $cnt = count($binds);
            $query = $this->query;
            if($this->binds) {
                foreach($this->binds as $ph => $pv) {
     // Escape the string.
     $query = str_replace(":$ph", "'".mysql_real_escape_string($pv)."'", $query);
                }
            }
            $this->result = mysql_query($query, $this->conn);
            if(!$this->result) {
                throw new $this->exception;                
            }
            if(!is_resource($this->result)) { // insert|update|delete|replae, not enough?
                //return the count of affected rows.
                return $this->affected_rows = mysql_affected_rows($this->conn);
            }
            return $this;
        } catch (MysqlException $e) {
            $e->displayError();
            exit;
        }
    }    
    
    public function get_all($obj = "") {
        try {
            if($obj == "")
                return $this->fetchall_obj();
            else if($obj == "array")
                return $this->fetchall_array();        
        } catch (MysqlException $e) {
            $e->displayError();
        }
    }
    
    // get one row.
    // this function also check whether there is no result.
    public function get_row($obj = "") {
        try {
            if($obj == "")
                return $this->fetch_obj();
            else if($obj == "array")
                return $this->fetch_array();    
        } catch (MysqlException $e) {
            $e->displayError();
        }
    }
    
    // get one val.
    public function get_var() {
        try {
            $val = $this->fetch_row();
            return $val[0];
        } catch (MysqlException $e) {
            $e->displayError();
        }
    }

    public function _flush() {
        $this->result = null;
    }
};

class MysqlException extends Exception {
    protected $backtrace;
    public function __construct($message=false, $code=false) {
        if(!$message) {
            $this->message = mysql_error();
        } else {
            $this->message = $message;
        }
        if(!$code) {
            $this->code = mysql_errno();
        } else {
            $this->code = $code;
        }
        $this->backtrace = debug_backtrace();        
    }
    
    public function displayError() {
        if(SHOWERROR) {
            //elcCoreApi::bypass_header();
            $this->DBerrorPage();
                        
        } else {
            // Append this to a log file.
            $log_msg = $this->_error_log();
            $this->appendToLog($log_msg);
        }
    }
    
    // log errors
    public function _error_log() {
        unset($this->backtrace);
        ob_start();
        echo "********** DB Error: ".$_SERVER['SCRIPT_NAME']." **********\n\n";
        print_r($this);            
        echo "********** Date: ".date('m-d-Y H:i:s')." **********\n\n";
        $output = ob_get_contents();
        ob_end_clean();
        return $output; 
    }
    
    public function appendToLog($log = "") {
        if(defined('dbErrorPath')):
            // check the dir first, if not create.
            // file based log.
   //echo dirname(dbErrorPath);
            if ($this->is_empty_folder(dirname(dbErrorPath))) mkdir(dirname(dbErrorPath), 0777); 
            @error_log($log, 3, dbErrorPath);
        else:
            @error_log($log, 3, 'dberror.log');
        endif;
    }    
 function is_empty_folder($dir) {
  if (is_dir($dir)) {
     $dl=opendir($dir);
     if ($dl) {
      while($name = readdir($dl)) {
       if (!is_dir($name)) {
        return false;
        break;
     }
      }
      closedir($dl);
     }
     return true;
  }
  else return true;
 }

    // Default DB error page.
    public function DBerrorPage() {
        $charset = charset;
        echo '
        <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
        <html xmlns="http://www.w3.org/1999/xhtml">
        <head>
            <title>Database ? Error</title>
            <meta http-equiv="Content-Type" content="text/html; charset=$charset" />
            <style media="screen" type="text/css">
            <!--
            html {
                background: #eee;
            }
            body {
                background: #fff;
                color: #000;
                font-family: Verdana, "Times New Roman", Times, serif;    
                font-size: 12px;                                
            }            
            #infldset {
                padding-left: 8px;
            }
            -->
            </style>
        </head>
        <body>
        <div align="left">
        <fieldset><legend> Database Error! </legend>
        <br />
        <div id="infldset">
  ';
        foreach($this as $field_name => $error_val) {    
            if($field_name != backtrace)
                echo strtoupper($field_name).": ". $error_val."<br />";
        }
        echo "<br />-- Backtrace a file with an array set --";
        echo "<pre>";
        print_r($this->backtrace[1]);
        echo "</pre>";
                    
        echo '
        </div>        
        </fieldset>
        </div>
        </body><html>            
  ';
        exit;    
    }    
};

class dbconn_production_site extends dbconn {
    protected $user      = DB_USER;
    protected $pass      = DB_PASS;
    protected $dbhost    = DB_HOST;
    protected $dbname    = DB_NAME;
    protected $exception = "MysqlException_production_site";
        
    public function __construct() {
        // Empty.
    }
};

class MysqlException_production_site extends MysqlException {
    
    public function displayError() {
        if(SHOWERROR) {
            $this->DBerrorPage();            
        } else {
            // Append this to a log file.
            $log_msg = $this->_error_log();
            $this->appendToLog($log_msg);
        }
    }
    
    // Default DB error page.
    public function DBerrorPage() {
        $charset = charset;
  //exit;
        echo '
        <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
        <html xmlns="http://www.w3.org/1999/xhtml">
        <head>
            <title>Production site database ? Error</title>
            <meta http-equiv="Content-Type" content="text/html; charset=$charset" />
            <style media="screen" type="text/css">
            <!--
            html {
                background: #eee;
            }
            body {
                background: #fff;
                color: #000;
                font-family: Verdana, "Times New Roman", Times, serif;    
                font-size: 12px;                                
            }            
            #infldset {
                padding-left: 8px;
            }
            -->
            </style>
        </head>
        <body>
        <div align="left">
        <fieldset><legend> Production site database Error! </legend>
        <br />
        <div id="infldset">
  ';
        foreach($this as $field_name => $error_val) {    
            if($field_name != backtrace)
                echo strtoupper($field_name).": ". $error_val."<br />";
        }
        echo "<br />-- Backtrace a file with an array set --";
        echo "<pre>";
        print_r($this->backtrace[1]);
        echo "</pre>";
                    
        echo '
        </div>        
        </fieldset>
        </div>
        </body><html>            
  ';
        exit;    
    }            
};

?>

댓글목록

등록된 댓글이 없습니다.

Total 612건 29 페이지
게시물 검색

회원로그인

접속자집계

오늘
240
어제
225
최대
1,347
전체
154,999
Latest Crypto Fear & Greed Index

그누보드5
Copyright © 서방님.kr All rights reserved.