<?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();
}
}
?>
操作数据库
最新推荐文章于 2024-11-02 08:30:00 发布