燕十八公益PHP培训 课堂地址:YY频道88354001 学习社区:www.zixue.it
<?php
class mysql {
private $conf=null;
static public $my=null;
private $conn=null;
private $log=null;//日志对象
private function __construct(){
$this->conf=conf::getIns();
$this->conn=$this->connect($this->conf->host,$this->conf->user,$this->conf->pwd);
$this->selectdb($this->conf->dbname);
$this->query('set names '.$this->conf->charset);
}
public static function getIns(){
if(!(self::$my instanceof self)){
self::$my=new self;
}
return self::$my;
}
public function connect($h,$u,$p){
return mysql_connect($h,$u,$p);
}
//执行sql语句
public function query($sql){
$res=mysql_query($sql,$this->conn);
log::write($sql);
return $res;
}
//选择数据库
private function selectdb($dbname){
$sql='use '.$dbname;
$this->query($sql);
}
//返回多行记录的数组
function getAll($sql){
$res=$this->query($sql);
$list=array();
while($row=mysql_fetch_assoc($res)){
$list[]=$row;
}
return $list;
}
//返回一行记录
function getRow($sql){
$res=$this->query($sql);
$row=mysql_fetch_assoc($res);
return $row;
}
function __destruct(){
mysql_close();
}
//自动操作插入,更新
function autoExecute($table,$data,$action='insert',$where=''){
//取得字段和值
$value="";
foreach($data as $list){
if(is_string($list)){//判断数组的值是否为字符串
$value.="'".$list."',";//是字符串加上引号
}else{
$value.=$list.',';
}
}
$value=trim($value,',');
$field=implode(',',array_keys($data));//取得键值作为字段
//根据action执行相应sql操作
if($action=='insert'){
$sql="insert into ".$table."(".$field.") values(".$value.")";
return $this->query($sql);
}else if($action='update'){
$newvalue=null;
foreach($data as $key=>$v){
if(is_string($v)){
$v="'$v'";
}
$newvalue.="$key".'='.$v.',';
}
$newvalue=trim($newvalue,',');
$sql="update $table set ".$newvalue.' where '.$where;
return $this->query($sql);
}
}
//返回单个值
function getOne($sql){
$res=$this->query($sql);
log::write($sql);
$row=mysql_fetch_row($res);
return $row[0];
}
//UPDATE 或 DELETE 查询所影响的记录行行数
public function affected_rows(){
return mysql_affected_rows($this->conn);
}
//取得上一步 INSERT 操作产生的 ID
public function getInsertId(){
return mysql_insert_id($this->conn);
}
}
?>