<?php
abstract class dao {
protected static $_conn; //單態串連
protected $_error; //錯誤資訊
protected $_errno; //錯誤號碼
protected $_perPageRecord; //每頁顯示幾條資料
protected $_currentTime;
protected $_recordCount;
public function __construct(){
}
//根據id尋找一條記錄
public function findById( $table, $id ){
$sql = "select * from {$table} where id={$id}";
return $this->uniqueQuery( $sql );
}
// 連資料庫
private function _connect(){
if( !is_resource( self::$_conn ) ){
self::$_conn = mysql_connect(
LOCALHOST,
MYSQL_USER,
MYSQL_PASS
);
mysql_select_db( MYSQL_DATABASE_NAME, self::$_conn );
mysql_query( "set names " . MYSQL_CODE, self::$_conn );
}
}
//檢查並執行查詢
private function _check_query( $result, $sql ){
if( !$result ){
$this->_error = mysql_error();
$this->_errno = mysql_errno();
$this->_error( "invalid SQL: " . $sql );
}
}
//設定每頁顯示的數量(用於分頁,當query的offset為空白時,此值無用
public function setPerPageRecord( $perPageRecord ){
$this->_perPageRecord = $perPageRecord;
}
//執行SQL並返回結果
protected function _sendSQL( $sql, $offset = false ){
$this->_connect();
if( is_numeric( $offset ) && is_numeric( $this->_perPageRecord ) ){
$sql = $sql . " limit {$offset}, " . $this->_perPageRecord;
}
$result = mysql_query( $sql, self::$_conn );
$this->_check_query( $result, $sql );
return $result;
}
//取得多條資料集
public function query( $sql, $offset = false ){
$result = $this->_sendSQL( $sql, $offset );
$datas = array();
while( $row = mysql_fetch_array( $result ) ){
$datas[] = $row;
}
return $datas;
}
//取得記錄總數,假如不分頁
public function getRecordCount( $sql ){
$result = $this->_sendSQL( $sql );
return $this->_recordCount = mysql_num_rows( $result );
}
//取得總頁數
public function getTotalPage(){
}
//取得唯一一條記錄
public function uniqueQuery( $sql ){
$result = $this->_sendSQL( $sql );
return mysql_fetch_array( $result );
}
//取得多個值 (select單個欄位時用)
public function fetchValues( $sql, $offset = false ){
$result = $this->_sendSQL( $sql, $offset );
$datas = array();
while( $row = mysql_fetch_array( $result ) ){
$datas[] = $row[0];
}
return $datas;
}
//錯誤處理
private function _error( $msg ){
printf("</td></tr></table><b>Database error:</b> %s<br>/n", $msg);
printf("<b>MySQL Error</b>: %s (%s)<br>/n",
$this->_errno,
$this->_error);
die("Session halted.");
}
//取得某一值
public function fetchValue( $sql ){
$result = $this->_sendSQL( $sql );
$value = mysql_fetch_row( $result );
return $value[0];
}
//執行非查詢語句
public function execute( $sql ){
$this->_sendSQL( $sql );
return mysql_insert_id( self::$_conn );
}
//執行刪除語句,要有傳回值return,否則無法獲得正確結果
public function deletesql( $sql ){
return $this->_sendSQL( $sql );
}
//關閉資料庫
public function close(){
mysql_close( self::$_conn );
}
//解構函式
public function __destruct(){
@$this->close();
}
}
?>