trackPageView(); ?> " width="0" height="0" />

mysql数据库封装

惜梦忆 2019-5-20 0 379
<?php
namespace Db;

/**
 * mysql数据库封装操作类
 * 请使用静态DbOperate::getInstance($config)实例化对象
 * 
 * $config['db']['host'] = "localhost";
 * $config['db']['user'] = "root";
 * $config['db']['pwd'] = "";
 * $config['db']['dbname'] = "ceshi";
 * $config['db']['port'] = "3306";
 * $config['db']['charset'] = "utf8";
 * 
 * @author 惜梦忆
 *
 */
class DbOperate
{
    private $host;//数据库地址
    private $port;//数据库端口
    private $user;//数据库用户名
    private $pwd;//数据库密码
    private $dbname;//数据库名字
    private $charset;//设置字符集
    private static $_instance = NULL;//单例模式
    private $link = null;//保存数据库连接
    private $error = array();//保存数据库错误信息
    
    /**
     * 创建数据库连接  并保存连接
     * @param 包含数据库配置的数组 $config
     */
    private function __construct($config){
        $this->iniParam($config);
        $this->link = mysqli_connect($this->host,$this->user,$this->pwd,$this->dbname,$this->port);
        mysqli_set_charset($this->link, $this->charset);
        if (mysqli_connect_errno($this->link)){
            $this->error = "连接 MySQL 失败: " . mysqli_connect_error();
        }
    }
    
    /**
     * 将配置信息数组解析 并存入成员变量
     * @param 包含数据库配置的数组 $config
     */
    private function iniParam($config){
        $this->host = isset($config['db']['host'])? $config['db']['host'] : '';
        $this->port = isset($config['db']['port'])? $config['db']['port'] : '3306';
        $this->user = isset($config['db']['user'])? $config['db']['user'] : '';
        $this->pwd = isset($config['db']['pwd'])? $config['db']['pwd'] : '';
        $this->charset = isset($config['db']['charset'])? $config['db']['charset'] : '';
        $this->dbname = isset($config['db']['dbname'])? $config['db']['dbname'] : '';
    }
    
    /**
     * 单例模式 用于实例化此类
     * @param 数据库配置数组 $config
     * @return \Db\DbOperate
     */
    public static function getInstance($config = array()){
        if (is_null(self::$_instance)){
            self::$_instance = new DbOperate($config);
        }
        return self::$_instance;
    }
    /**
     * 防止被二次实例化
     */
    private function __clone(){}
    
    /**
     * 查询一条结果
     * @param 表名 $tbname
     * @param 约束条件 $config
     * @return 成功返回一条结果  失败返回错误
     */
    public function fetch($tbname,$config = null){
        $sql = $this->buildSql($tbname,$config);
        echo $sql;
        $res = mysqli_query($this->link, $sql);
        $this->returnError($res);
        return mysqli_fetch_row($res);
    }
    
    /**
     * 查询数据表所有数据
     * @param 表名 $tbname
     * @param 约束条件 $config
     * @return 成功返回结果集  失败返回错误信息
     */
    public function fetchAll($tbname,$config = null){
        $sql = $this->buildSql($tbname,$config);
        $res = mysqli_query($this->link, $sql);
        $this->returnError($res);
        return mysqli_fetch_all($res);
    }
    
    /**
     * 插入一条数据
     * @param 表的名字 $tbname
     * @param 插入的数据  数组形式 $data
     * @return 成功返回主键id 失败返回错误
     */
    public function add($tbname,$data){
        $key = array_keys($data);
        $fields = implode(",", $key);
        $value = implode("','", $data);
        $sql = "insert into $tbname ($fields) values ('".$value."')";
        $res = mysqli_query($this->link, $sql);
        $this->returnError($res);
        return mysqli_insert_id($this->link);
    }
    /**
     * 更新数据
     * @param 表名 $tbname
     * @param 修改的数据 一维数组 $data
     * @param 修改条件 $where
     * @return \Db\返回数据库的错误
     */
    public function save($tbname,$data,$where = null){
        $arr = array();
        $fields = array_keys($data);
        foreach ($data as $key=>$value){
            $arr[] =  $key."='".$value."'";
        }
        $value = implode(',', $arr);
        $where = ($where != null ? 'where '.$where : null);
        $sql = "update $tbname set $value $where ";
        $res = mysqli_query($this->link, $sql);
        return $this->returnError($res);
    }
    /**
     * 删除数据
     * @param 表名 $tbname
     * @param 删除条件 不写条件会全删 $where
     * @return \Db\返回数据库的错误
     */
    public function delete($tbname,$where = null){
        $where = ($where != null ?"where $where":null);
        $sql = "delete from $tbname $where";
        $res = mysqli_query($this->link, $sql);
        return $this->returnError($res);
    }
// 查询所有
// 查询一条
// 插入一条
// 限制查询
// 删除全部
// 删除一条
    /**
     * 构建sql语句  减少重复代码
     * @param 表的名字 $tbname
     * @param 约束条件 $config
     * @return 返回构建的sql语句
     */
    private function buildSql($tbname,$config = null){
        if (isset($config['fields']) && $config['fields'] != ''){
            $sql = 'select ' . $config['fields'] . ' from ' . $tbname;
        } else {
            $sql = "select * from $tbname";
        }
        
        if (isset($config['where']) && $config['where'] != '') {
            $sql = $sql . ' where '. $config['where'];
        }
        if (isset($config['group']) && $config['group'] != '') {
            $sql = $sql . ' group by ' . $config['group'];
        }
        if (isset($config['having'])&&$config['having'] != '') {
            $sql = $sql . ' having '.$config['group'];
        }
        if (isset($config['limit']) && $config['limit'] != '') {
            $sql = $sql . " limit " . $config['limit'];
        }
        return $sql;
    }
    /**
     * 
     * @param 数据库结果集 $res
     * @return 返回数据库的错误
     */
    private function returnError($res){
        if (!$res){
            return mysqli_error_list($this->link);
        }
    }
    
//     public function getError(){
//         return $this->error;
//     }
    /**
     * 对象使用完释放资源
     */
    public function __destruct(){
        mysqli_close($this->link);
    }

}


---------------------------------------------------------------------------------------------------------------------------------------

<?php use Db\DbOperate; require './Db/DbOperate.class.php'; $config['db']['host'] = "localhost"; $config['db']['user'] = "root"; $config['db']['pwd'] = ""; $config['db']['dbname'] = "ceshi"; $config['db']['port'] = "3306"; $config['db']['charset'] = "utf8"; $db = DbOperate::getInstance($config); // print_r($db->fetch('users'))//查询一条记录 // $config['where'] = 'userid=3';//指定条件查询 // $config['limit'] = '2,1';//limit限制查询 // $config['fields'] = 'name,tel'; // print_r($db->fetch('users',$config));//查询一条记录 // print_r($db->fetchAll('users',$config)); //查询所有 $data = array( //     'id' => '1',     'name' => 'hmw',     'age' => '99', ); $where ='id=6'; var_dump($db->save('test', $data,$where)); // var_dump($db->delete('st',$where)); // print_r($db->getError());

------

#php##mysql##封装#

免责声明:本文仅代表作者个人观点,与本网站无关。其原创性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容、文字的真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
作者: 惜梦忆 本文最后编辑于2019-5-20 08:07:28
惜梦忆

一个编程小白

作者的微博

发表评论: