host=!empty($config['host'])? $config['host']:"localhost"; $this->port=!empty($config['port'])? $config['port']:"3306"; $this->user=!empty($config['user'])? $config['user']:"root"; $this->password=!empty($config['password'])? $config['password']:""; $this->charset=!empty($config['charset'])? $config['charset']:"utf8"; $this->dbname=!empty($config['dbname'])? $config['dbname']:""; $this->link= mysql_connect ("{$this->host}:{$this->port}", "{$this->user}","{$this->password}") or die('執行失敗'); $this->setCharset($this->charset); $this->useDBname($this->dbname); } //單例設計模式 static $temp=null; static function getClass(){ if(!isset(self::$temp)){ $class=new self(); }else{ return self::$temp; } } //可以設定編碼 function setCharset($charset){ mysql_query("set names $charset"); } //可以設定要串連的資料庫 function useDBname($dbname){ mysql_query("use $dbname"); } //可以關閉資料庫 function closeDB(){ mysql_close($this->link); echo"關閉成功!"; } //執行一條增刪改語句,返回真假結果 function exec($sql){ $result=$this->query($sql); return true; } //返回一行的查詢資料 function gerRow($sql){ $result=$this->query($sql); $array=mysql_fetch_array($result); mysql_free_result($result);//釋放資源 return $array; } //返回多行的查詢資料 function getRows($sql){ $result=$this->query($sql); $arr=array(); while($array=mysql_fetch_array($result)){ $arr[]=$array; } mysql_free_result($result);//釋放資源 return $arr; } //返回一個資料的語句,可以返回一個直接值 function getOneData($sql){ $result=$this->query($sql); $array=mysql_fetch_array($result); $data=$array[0]; mysql_free_result($result);//釋放資源 return $data; } //可以執行任何sql語句,並進行錯誤處理,或返回執行結果 function query($sql){ $result=mysql_query($sql,$this->link); if($result===false){ echo"執行失敗,請參看如下資訊:"; echo"
錯誤代號:".mysql_errno(); echo"
錯誤資訊:".mysql_error(); echo"
錯誤語句:".$sql; die(); }else{ return $result; } }}