一个简单的封装mysql函数

<?php 
/**
 *@author will sun@lanvane.com
 *@link http://www.lanvane.com
 *@since 0.1 2016年8月8日
 *@copyright GPL 
*/
/**
*连接mysql数据库
*
*/
require('./config.php');
//echo $GLOBALS['doyoConfig']['db']['host'];
class SqlSet{
   public function conn(){
      static $con=null;
      if ($con==null) {
//       $cfg=require(ROOT. '/lib/MysqlConfig.php');
//        $cfg=require('./MysqlConfig.php');
         $con=mysql_connect($GLOBALS['doyoConfig']['db']['host'],$GLOBALS['doyoConfig']['db']['login'],$GLOBALS['doyoConfig']['db']['password'])or die('连接数据库失败');
         mysql_query('use '.$GLOBALS['doyoConfig']['db']['database'],$con)or die('选择库失败');
         mysql_query('set names utf8',$con)or die('设置字符集失败');
      }
      return $con;
   }

   public function mQuery($sql){
      $rs=mysql_query($sql,$this->conn());
//    if ($rs) {
//       $this->mLog($sql);
//    }else{
//       $this->mLog($sql."\n".mysql_error());
//    }
      return $rs;
      // return mysql_query($sql,conn());
   }
   //log日志记录功能
   public function mLog($str){
      $filename='./log/'.date('Ymd').'.txt';
      // $filename='../log/'.date('Ymd').'.txt';
      $log=date('Y/m/d H:i:s').'   '.$str."\n"."=================================="."\n";
      // echo $log;
      return file_put_contents($filename,$log,FILE_APPEND);
   }
   //获取多行数据
   function getAll($sql){
      $rs=$this->mQuery($sql);
      if (!$rs) {
         return false;
      }
      $data=array();
      while ($row=mysql_fetch_assoc($rs)) {
         $data[]=$row;
      }
      return $data;
   }
   //获取单行数据
   function getOne($sql){
      $rs=$this->mQuery($sql);
      if (!$rs) {
         return false;
      }
      return mysql_fetch_assoc($rs);
   }
/**
*自动凭借insert update sql语句,并且调用mquery(),去执行sql
* @param str $biao 表名
* @param arr $date  接收到的数据是一个一维数组
* @param str $act 动作 默认为'insert'
*
*/
   function setSql($biao,$date,$act='insert',$where=0){
      if ($act=='insert') {
         $sql="insert into $biao(";
         $sql.=implode(',', array_keys($date)).")values('";
         $sql.=implode("','", array_values($date))."')";
         return $this->mQuery($sql);
         // return $sql;
      }
      if($act=='update'){
         $sql="update $biao set ";
         foreach ($date as $k => $v) {
            $sql .=$k."='".$v."',";
         }
         $sql=rtrim($sql,',')." where ".$where;
         return $this->mQuery($sql);
         // return $sql;

      }

   }
   //取得上一次insert 的主键id
   function getLastId(){
      return $this->mysql_insert_id(conn());
   }
}


// $cs='select * from cat';
// var_dump(getOne($cs));

// $date=array('catname'=>'1214');
// var_dump(setSql($date));
 // print_r(setSql('cat',$date,'insert'));
 // print_r(setSql('cat',$date,'update',"catname='1213'"));
HTTPROOT | 自学PHP | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 石头哥 |微信小程序 |木讯 |备案
Copyright © 1998 - 2016 HTTPROOT.COM. All Rights Reserved httproot.com 版权所有