Loading... 自制php操作mysql工具類(DB.class.php) DB.class.php 復制代碼 <?php class DB{ //主機地址 var $host; //用戶名 var $username; //密碼 var $password; //數據庫名 var $dbname; //字符集 var $charset; //數據庫連接對象,主要用在mysql_query($sql,$this->con); private $con; //外界獲取的mysqlDB類操作對象 public static $dao; //獲得mysqlDB類對象(單例) public static function getInstance($config){ if(!isset(self::$dao)){ self::$dao = new self($config); } return self::$dao; } //private禁止外部new,減少new帶來的開銷,并設置默認的配置。 private function __construct($config){ $this->host = isset($config['host'])?$config['host']:'localhost'; $this->port = isset($config['port'])?$config['port']:'3306'; $this->username = isset($config['username'])?$config['username']:'root'; $this->password = isset($config['password'])?$config['password']:'root'; $this->dbname = isset($config['dbname'])?$config['dbname']:'test'; $this->charset = isset($config['charset'])?$config['charset']:'utf8'; //連接數據庫 $this->con = $this->connect(); //設置數據庫名,默認為test $this->useDb($this->dbname); //設置字符集,默認為utf8。 $this->setCharset($this->charset); } //禁止外部克隆 private function __clone(){ } //連接不成功在這個分段找。 ////////////////////////////////////////////////////// //連接數據庫 public function connect(){ $con = mysql_connect("$this->host:$this->port","$this->username","$this->password") or die("連接數據庫失敗"); return $con; } //1.執行增、刪、改sql語句 public function exec($sql){ $res = mysql_query($sql,$this->con); if($res){ // echo "<br/>sql語句:".$sql."<br>"; // var_dump($res); return true; //要是增刪改有問題可以在這里輸出sql調試。 }else{ echo "<br/>sql語句:".$sql; echo "<br/出錯信息>:".mysql_error(); echo "<br/出錯代碼>:".mysql_errno(); exit; } } //額外設置字符集 public function setCharset($charset){ $sql = "set names '$charset'"; $this->exec($sql) or die("set"); //die(); } //額外設置數據庫 public function useDb($dbname){ $sql = "use $dbname"; $this->exec($sql) or die("use");//or die()函數前面需返回對應的true或false; } //////////////////////////////////////////////////////// //查找出錯在這個部分找。 //4.將查到的結果集轉為單個數據,這里是索引數組的第一個字段。 public function getOne($sql){ $rec = mysql_query($sql,$this->con); $res = mysql_fetch_row($rec); if($res){ return $res[0]; }else{ return false; } } //可能修改的函數全部放在上面,以便查找。下方函數基本不會修改。 //編號1~4是高頻率使用的函數。 //2.獲取一行數據(一維) public function getRow($sql){ $rec = mysql_query($sql,$this->con); $res = mysql_fetch_assoc($rec); if($res){ return $res; }else{ return false; } } //3.獲取所有數據(二維) public function getAll($sql){ $rec = mysql_query($sql,$this->con); $arr = array();//定義 一個數組 while($res = mysql_fetch_assoc($rec)){ $arr[] = $res; } if($arr){ return $arr; }else{ return false; } } } $dao = DB::getInstance(null); ?> <?php include_once("DB.class.php"); $sql = "select * from goods where id = 1"; //.獲取一行數據(一維) $res = $dao->getRow($sql); var_dump($res); //以上的getRow函數只是舉例,具體如何使用這個工具,首先要在你的php文件中include這個工具類,即include_once("DB.class.php"); //1.要看你的sql語句查回的數據是一維的,還是二維的,或者單個數據。 //對應的函數是getROW,getAll,getOne。 //2.增刪改統一用exec。 //3.數據庫的連接配置在構造構造函數中修改。 ?> 注意事項: 1.文件DB.class.php建好后。 2.在你需要操作數據庫接的文件中include這個文件,上面有示例。 3.使用之前必須把數據庫名改成你的數據庫名。這個是最重要的,也是最容易忘記的。 復制代碼 引用 復制代碼 <?php include_once("DB.class.php"); $sql = "select * from goods where id = 1"; //.獲取一行數據(一維) $res = $dao->getRow($sql); var_dump($res); //以上的getRow函數只是舉例,具體如何使用這個工具,首先要在你的php文件中include這個工具類,即include_once("DB.class.php"); //1.要看你的sql語句查回的數據是一維的,還是二維的,或者單個數據。 //對應的函數是getROW,getAll,getOne。 //2.增刪改統一用exec。 //3.數據庫的連接配置在構造構造函數中修改。 ?> 復制代碼 注意事項: 1.文件DB.class.php建好后。 2.在你需要操作數據庫接的文件中include這個文件,上面有示例。 3.使用之前必須把數據庫名改成你的數據庫名。這個是最重要的,也是最容易忘記的。 === 數據庫連接類 DB.class.php 復制代碼 <?php /** * 數據庫操作類 */ class DB { private $link_id; private $handle; //日志文件句柄 private $is_log; private $time; public function __construct() { header("Content-type: text/html; charset=utf-8"); $this->time = $this->microtime_float(); require_once 'configs/config.db.php'; $this->connect($db_config["hostname"], $db_config["username"], $db_config["password"], $db_config["database"], $db_config["pconnect"]); $this->is_log = $db_config["log"]; if($this->is_log){ $this->handle = fopen($db_config["logfilepath"] . "dblog.txt", "a+"); } } /** * 連接數據庫 */ public function connect($dbhost, $dbuser, $dbpw, $dbname, $pconnect = 0, $charset ='utf8') { if($pconnect == 0){ $this->link_id = mysql_connect($dbhost, $dbuser, $dbpw, true); if(!$this->link_id){ $this->halt("數據庫連接失敗"); } }else{ $this->link_id = mysql_pconnect($dbhost, $dbuser, $dbpw); if(!$this->link_id){ $this->halt("數據庫長連接失敗"); } } if(!mysql_select_db($dbname, $this->link_id)){ $this->halt("數據庫選擇失敗"); } mysql_query("set names " . $charset); } /** * 查詢 * Enter description here ... * @param unknown_type $sql */ public function query($sql){ $this->write_log("查詢 " . $sql); $query = mysql_query($sql, $this->link_id); if(!$query){ $this->halt("查詢失敗 " . $sql); } return $query; } /** * 獲取一條記錄(MYSQL_ASSOC,MYSQL_NUM,MYSQL_BOTH) * Enter description here ... * @param $sql */ public function get_one($sql, $result_type = MYSQL_ASSOC){ $query = $this->query($sql); $rt = mysql_fetch_array($query, $result_type); $this->write_log("獲取一條記錄 " . $sql); return $rt; } /** * 獲取全部記錄 * Enter description here ... * @param unknown_type $sql * @param unknown_type $result_type */ public function get_all($sql, $is_page = false, $page_num = 10, $result_type = MYSQL_ASSOC){ if(!$is_page){ $query = $this->query($sql); $i = 0; $rt = array(); while ($row = mysql_fetch_array($query, $result_type)) { $rt[$i++] = $row; } $this->write_log("獲取全部記錄(無翻頁)" . $sql); }else{ $rt = $this->page($sql, $page_num, $result_type); } return $rt; } /** * 獲取全部數據(帶翻頁) * Enter description here ... * @param $sql sql語句 * @param $page_num 每頁顯示記錄條數 */ public function page($sql, $page_num, $result_type){ session_start(); $query = $this->query($sql); $all_num = mysql_num_rows($query); //總條數 $page_all_num = ceil($all_num / $page_num); //總頁數 $page = empty($_GET['page']) ? 1 : $_GET['page']; //當前頁數 $page = (int)$page; //安全強制轉換 $limit_str = ($page - 1) * $page_num; //記錄起始數 $sql .= " limit $limit_str, $page_num"; $query = $this->query($sql); $i = 0; $rt = array(); while ($row = mysql_fetch_array($query, $result_type)) { $rt[$i++] = $row; } $this->write_log("獲取翻頁記錄(帶翻頁)" . $sql); $_SESSION["page_all_num"] = $page_all_num; $_SESSION["next"] = $page >= $page_all_num ? $page_all_num : $page + 1; $_SESSION["pre"] = $page <= 1 ? 1 : $page - 1; return $rt; } /** * 插入 * Enter description here ... * @param unknown_type $table * @param unknown_type $dataArray */ public function insert($table,$dataArray) { $field = ""; $value = ""; if( !is_array($dataArray) || count($dataArray) <= 0) { $this->halt('沒有要插入的數據'); return false; } foreach ($dataArray as $key => $val){ $field .="$key,"; $value .="'$val',"; } $field = substr( $field,0,-1); $value = substr( $value,0,-1); $sql = "insert into $table($field) values($value)"; $this->write_log("插入 ".$sql); if(!$this->query($sql)) return false; return true; } /** * 更新 * Enter description here ... * @param unknown_type $table * @param unknown_type $dataArray * @param unknown_type $condition */ public function update( $table,$dataArray,$condition="") { if( !is_array($dataArray) || count($dataArray)<=0) { $this->halt('沒有要更新的數據'); return false; } $value = ""; while( list($key,$val) = each($dataArray)) $value .= "$key = '$val',"; $value .= substr( $value,0,-1); $sql = "update $table set $value where 1=1 and $condition"; $this->write_log("更新 ".$sql); if(!$this->query($sql)) return false; return true; } /** * 刪除 * Enter description here ... * @param unknown_type $table * @param unknown_type $condition */ public function delete( $table,$condition="") { if( empty($condition) ) { $this->halt('沒有設置刪除的條件'); return false; } $sql = "delete from $table where 1=1 and $condition"; $this->write_log("刪除 ".$sql); if(!$this->query($sql)) return false; return true; } /** * 返回結果集 * Enter description here ... * @param unknown_type $query * @param unknown_type $result_type */ public function fetch_array($query, $result_type = MYSQL_ASSOC){ $this->write_log("返回結果集"); return mysql_fetch_array($query, $result_type); } /** * 獲取記錄條數 * Enter description here ... * @param unknown_type $results */ public function num_rows($results) { if(!is_bool($results)) { $num = mysql_num_rows($results); $this->write_log("獲取的記錄條數為".$num); return $num; } else { return 0; } } /** * 獲取最后插入的id * Enter description here ... */ public function insert_id() { $id = mysql_insert_id($this->link_id); $this->write_log("最后插入的id為".$id); return $id; } /** * 關閉數據庫連接 * Enter description here ... */ public function close() { $this->write_log("已關閉數據庫連接"); return @mysql_close($this->link_id); } /** * 錯誤提示 */ private function halt($msg = ''){ $msg .= "\r\n" . mysql_error(); $this->write_log($msg); die($msg); } /** * 寫入日志文件 */ public function write_log($msg = ''){ if($this->is_log){ $text = date("Y-m-d H:i:s") . " " . $msg . "\r\n"; fwrite($this->handle, $text); } } /** * 獲得毫秒數 */ public function microtime_float() { list($usec, $sec) = explode(" ", microtime()); return ((float)$usec + (float)$sec); } /** * 析構函數 * Enter description here ... */ public function __destruct(){ $use_time = ($this->microtime_float()) - ($this->time); $this->write_log("完成整個查詢任務,所用時間為 " . $use_time); if($this->is_log){ fclose($this->handle); } } } ?> 復制代碼 config.db.php配置文件 復制代碼 <?php $db_config = array ( 'hostname' => 'localhost', 'username' => 'root', 'password' => '123456', 'database' => 'child_games', 'charset' => 'utf8', 'pconnect' => 0, //是否使用持久連接(0關/1開) 'log' => 1, //是否開啟日志(0關/1開) 'logfilepath' => './' //日志文件目錄 ); ?> 復制代碼 最后修改: ? 允許規范轉載 打賞 贊賞作者 支付寶微信 贊 如果覺得我的文章對你有用,請隨意贊賞