php mssql server 2005数据库连接类
php教程 mssql server 2005数据库教程连接类
class msDriver{
public $error;
public $querynum=0;
public $link;
public $lastQuery;
public $lastInsert_id=0;
public $error_callback=array('record'); //record,ignore,report,abort
public $error_report_file=ROOT."/webdata/db.error.log";
function __construct($server='',$connectionInfo=array()){
if ($server){
$this->connect($server,$connectionInfo);
}
}
function __destruct(){
!$link && $link= &$this->link;
if ($link) sqlsrv_close( $link );
}
function connect($dbhost='(local)', $connectionInfo=array()){
$this->link=sqlsrv_connect($dbhost,$connectionInfo);
if (!$this->link) $this->halt();
}
/**
*查询过程
*
* @param string $sql
* @param resource $link
* @return resource
*/
function query($sql="",$link=''){
!$link && $link= &$this->link;
$query=@sqlsrv_query($link,$sql);
$this->lastQuery=&$query;
if (!$query) $this->halt();
$reg = "#insert into#";
if(preg_match($reg,$sql)){
$res = sqlsrv_query($link,"select @@IDENTITY as id");
$this->lastInsert_id = sqlsrv_get_field($res,0);
}
return $query;
}
/**
* 返回字段总数
*
* @param resource $result
* @return number
*/
function num_fields($result=''){
if (!$result) $this->halt();
return @sqlsrv_num_fields($result);
}
/**
* 返回字段值
*
* @param resource $result
* @param Int $fieldIndex
* @return value
*/
function result($result='',$fieldIndex=0){
if (!$result) $this->halt();
return sqlsrv_get_field($result,$fieldIndex);
}
/**
* 返回行数组
*
* @param unknown_type $result
* @return unknown
*/
function fetch_array($result,$type=SQLSRV_FETCH_ASSOC){ //SQLSRV_FETCH_NUMERIC,SQLSRV_FETCH_ASSOC,SQLSRV_FETCH_BOTH
!$result && $result=$this->lastQuery;
if (!$result) $this->halt();
$r=@sqlsrv_fetch_array($result,$type);
return is_array($r)?$r:0;
}
/**
* 返回影响的记录数
*
* @param resource $result
* @return number
*/
function affected_rows($result) {
if (!$result) $this->halt();
return sqlsrv_rows_affected($result);
}
function insert_id(){
return $this->lastInsert_id;
}
function freeResult($result){
!$result && $result=$this->lastQuery;
sqlsrv_free_stmt($result);
}
/**
* 错误的处理方式
*
*/
function halt(){
$err=$this->getEroor();
//var_dump($err['']);
if (in_array('record',$this->error_callback)){
$fp=fopen($this->error_report_file,'a+');
if ($fp){
fwrite($fp,"[".date("Y//m/dH:i:s")."](".$err['code'].")".$err['message'].",URL:".$_SERVER["REQUEST_URI"]."?".$_SERVER["QUERY_STRING"]."rn");
fclose($fp);
}
}
if (in_array('report',$this->error_callback)){
echo "
错误:[".date("Y//m/d H:i:s")."](".$err['code'].")".$err['message'];
}
if (in_array('abort',$this->error_callback)){
exit;
}
}
/**
* 返回查询错误
*
* @return array
*/
function getEroor(){
$err=sqlsrv_errors();
//return array('code'=>$err['code'],'message'=>$err['message']);
return is_array($err)?$err[0]:array();
}
}
补充:数据库,Mssql