封装一个MySQL工具类

MySQL工具类

功能:

  1. 单例创建工具类对象,并连接MySQL
  2. 对mysql_query做封装,错误时打印错误SQL语句、出错信息、出错码
  3. 查询方法1:返回查询的全部结果,并作为数组返回
  4. 查询方法2:返回第一行数据,并作为数据返回
  5. 查询方法3:返回第一行的第一列数据,并作为数据返回
host = isset($config['host'])?$config['host']:'localhost';
        $this->port = isset($config['port'])?$config['port']:'8889';
        $this->username = isset($config['username'])?$config['username']:'root';
        $this->password = isset($config['password'])?$config['password']:'root';
        $this->charset = isset($config['charset'])?$config['charset']:'utf8';
        $this->dbname = isset($config['dbname'])?$config['dbname']:'';

        $this->connect();
        //设定连接编码
        $this->setCharset($this->charset);
        //设定数据库
        $this->selectDb($this->dbname);
    }
    //禁止clone
    private function __clone(){}

    public function connect(){
        $this->resource = mysql_connect("$this->host:$this->port","$this->username","$this->password") or die("连接数据库失败");
    }
    public function setCharset($charset){
        $this->query("set name $charset");

    }
    public function selectDb($dbname){
        $this->query("use $dbname") or die('选择数据库失败');
    }
    /**
     * 执行最基本sql语句
     * @param  返回错误代码
     * @return 返回执行结果
     */
    public function query($sql){
        //执行失败
        if(!$result = mysql_query($sql,$this->resource)){
            echo "
sql语句:".$sql; echo "
:".mysql_error(); echo "
:".mysql_errno(); die(); } return $result; } /** * 功能执行select语句,返回2维数组 * 参数:$sql 字符串类型 select语句 */ public function getAll($sql){ $result = $this -> query($sql); $arr = array(); while($rec = mysql_fetch_assoc($result)){ $arr[] = $rec; } return $arr; } /** * 功能:返回一行数据作为一维数组 * 参数:$sql 字符串类型 select语句 */ public function getRow($sql){ $result = $this -> query($sql); if($rec2 = mysql_fetch_assoc($result)){ //如果fetch出来有数据,返回一维数组 return $rec2; } return false; } /** * 功能:返回select的第一行第一列 * 参数:$sql 字符串类型 select语句 */ public function getOne($sql){ $result = $this -> query($sql); $rec = mysql_fetch_row($result);//返回下标为数字的数组 if($rec == false){ return false; } return $rec[0]; } } ?>

昨天球队信息例子来展示如何使用。昨天内容戳这里

'localhost',
        'port'=>'8889',
        'username'=>'root',
        'password'=>'root',
        'charset'=>'utf8',
        'dbname'=>'php'
    );
    $dao = MySQLDB::getInstance($config);//$dao,Database Access Object 数据库操作对象(道层)

    //获得比赛里表数据
    $sql = "select t1.t_name as t1_name, m.t1_score, m.t2_score, t2.t_name as t2_name, m.m_time from `match` as m 
        left join `team` as t1 ON
        m.t1_id = t1.t_id  
        left join `team` as t2 ON 
        m.t2_id=t2.t_id;";
    $match_list=$dao->getAll($sql);
?>




    
    比赛列表


    
球队一比分球队二比赛时间
:
封装一个MySQL工具类_第1张图片
执行结果

你可能感兴趣的:(封装一个MySQL工具类)