封装一个mysql类(ggshop)
接口
abstract class db{
//连接服务器
public abstract function connect($n,$u,$p);
//发送查询
protected abstract function query($sql);
//查询单个数据
public abstract function getone($sql);
//查询单行数据
public abstract function getrow($row);
//查询多行数据 自动执行insert/update语句
public abstract function autoexecute($table,$data,$act='insert',$where='');
}
--------------------------------------------------------------------------------------------------------------
class mysql extends db{
private static $ins=null;
private $conn=null;
private $conf=array();
protected function __construct(){
$this->conf=conf::getins();
$this->connect($this->conf->host,$this->conf->user,$this->conf->pwd);
$this->select_db($this->conf->db);
$this->setchar($this->conf->char);
}
public function __destruct(){
}
public static function getins(){
if(!(self::$ins instanceof self)){
self::$ins=new self();
}
return self::$ins;
}
public function connect($h,$u,$p){
$this->conn=mysql_connect($h,$u,$p);
if(!$this->conn){
$err=new exception('连接失败');
throw $err;
}
}
public function select_db($db){
$sql='use '.$db;
$this->query($sql);
}
public function setchar($char){
$sql='set names '.$char;
return $this->query($sql);
}
public function query($sql){
$rs=mysql_query($sql,$this->conn);
log::write($sql);
return $rs;
}
public function
autoexecute($table,$arr,$mode='insert',$where='where 1 limit
1'){
if(!is_array($arr)){
return false;
}
if($mode=='update'){
$sql='update'.$table.'set';
foreach($arr as $k=>$v){
$sql.=$k."='".$v."',";
}
$sql=rtrim($sql,',');
$sql.=$where;
return $this->query($sql);
}
$sql='insert
into'.$table.'('.implode(',',array_keys($arr)).')';
$sql.='values(\'';
$sql.=implode("','",array_values($arr));
$sql.='\')';
}
public function getall($sql){
$rs=$this->query($sql);
$list=array();
while($row=mysql_fetch_assoc($rs)){
$list[]=$row;
}
return $list;
}
public function getrow($sql){
$rs=$this->query($sql);
return mysql_fetch_assoc($rs);
}
public function getone($sql){
$rs=$this->query($sql);
$row=mysql_fetch_row($rs);
return $row[0];
}
// 返回影响行数的函数
public function affected_rows(){
return mysql_affected_rows($this->conn);
}
// 返回最新的auto_increment列的自增长的值
public function insert_id(){
return mysql_insert_id($this->conn);
}
}