自己寫的mysql簡易數據庫類2

燕十八公益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);
   }
}







?>

發佈了35 篇原創文章 · 獲贊 0 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章