php數據庫類

想本身寫一個框架,便於理解php框架的總體運行體系,一步步來,這個是數據庫類。confing在下面。php

<?php

$config = include 'confing.php';
$m = new Model($config);
var_dump($m->table('user')->getByAge(18));
// $m->limit('0,5')->table('user')->field('age,name')->order('money desc')->where('id>1')->select();
//$data = $m->table('user')->field('id,age,name')->limit('0,1')->where('id>0')->order('age desc')->select();
/*$data = [
    'name'=>'成龍',
    'age'=>'25',
    'money'=>'9999'
];*/
// $insert = $m->table('user')->insert($data);
// $delete = $m->table('user')->where('id=4')->delete();
//$update = $m->table('user')->where('id=3')->update($data);
// $max = $m->table('user')->max('money');
// var_dump($m->sql);
// var_dump($max);

class Model
{
    //地址
    protected $host;
    //用戶名
    protected $user;
    //密碼
    protected $pwd;
    //庫名
    protected $dbname;
    //字符集
    protected $charset;
    //表前綴
    protected $prefix;

    //連接資源
    protected $link;
    //表名
    protected $tableName;

    //sql語句
    protected $sql;
    //存放查詢條件
    protected $options;


    //構造方法,成員變量初始化
    function __construct($config)
    {
        $this->host = $config['DB_HOST'];
        $this->user = $config['DB_USER'];
        $this->pwd = $config['DB_PWD'];
        $this->dbname = $config['DB_NAME'];
        $this->charset = $config['DB_CHARSET'];
        $this->prefix = $config['DB_PREFIX'];

        //鏈接數據庫
        $this->link = $this->connect();

        //獲得數據表名
        $this->tableName = $this->getTableName();

        //初始化options數組
        $this->initOptions();
    }

    protected function connect()
    {
        $link = mysqli_connect($this->host,$this->user,$this->pwd);
        
        if (!$link){
            
            die('數據庫鏈接失敗');
        }
        mysqli_select_db($link,$this->dbname);//選擇數據庫
        mysqli_set_charset($link,$this->charset);//設置字符集
        return $link;
    }

    protected function getTableName()
    {
        //1,已有成員變量
        if (!empty($this->tableName)) {
            return $this->prefix.$this->tableName;
        }
        //2,無成員變量
        $className = get_class($this);//得到類名字符串
        $table = strtolower(substr($className, 0, -5));//如ArticleModel截取表名截掉後五個字符並轉爲小寫
        return $this->prefix.$table;
    }

    protected function initOptions()
    {
        $arr = ['where','table','field','order','group','having','limit'];
        foreach ($arr as $value) {
            //數組內鍵對應的值清空
            $this->options[$value] = '';
            //table默認設置爲tableName
            if($value == 'table'){
                $this->options[$value] = $this->tableName;
            }elseif ($value == 'field') {
                $this->options[$value] = '*';
            }
        }
    }

    //field
    function field($field)
    {
        if (!empty($field)) {
            if (is_string($field)) {
                $this->options['field'] = $field;
            }elseif (is_array($field)) {
                $this->options['field'] = join(',',$field);
            }
        }
        return $this;
    }
    //table
    function table($table)
    {
        if (!empty($table)) {
            $this->options['table'] = $table;
        }
        return $this;
    }
    //where
    function where($where)
    {
        if (!empty($where)) {
            $this->options['where'] = 'where '.$where;
        }
        return $this;
    }
    //group
    function group($group)
    {
        if (!empty($group)) {
            $this->options['group'] = 'group by '.$group;
        }
        return $this;
    }
    //having
    function having($having)
    {
        if (!empty($having)) {
            $this->options['having'] = 'having '.$having;
        }
        return $this;
    }
    //order
    function order($order)
    {
        if (!empty($order)) {
            $this->options['order'] = 'order by '.$order;
        }
        return $this;
    }
    //limit
    function limit($limit)
    {
        if (!empty($limit)) {
            if (is_string($limit)) {
                $this->options['limit'] = 'limit '.$limit;
            }elseif (is_array($limit)) {
                $this->options['limit'] = 'limit '.join(',',$limit);
            }
        }
        return $this;
    }
    //select
    function select()
    {
        //預寫一個帶佔位符的sql
        $sql = 'select %FIELD% FROM %TABLE% %WHERE% %GROUP% %HAVING% %ORDER% %LIMIT%';
        //將options中值一次替換佔位符。

        $sql = str_replace(
            ['%FIELD%','%TABLE%','%WHERE%','%GROUP%','%HAVING%','%ORDER%','%LIMIT%'],
            [
            $this->options['field'],
            $this->options['table'],
            $this->options['where'],
            $this->options['group'],
            $this->options['having'],
            $this->options['order'],
            $this->options['limit']
            ],$sql);
        //保存sql語句
        $this->sql = $sql;
        //執行sql語句
        // echo $sql;die;
        return $this->query($sql);
    }
    //query
    function query($sql)
    {
        //清空options數組
        $this->initOptions();
        
        $result = mysqli_query($this->link,$sql);
        //提取結果集存放到數組中
        // var_dump($result);
        // die;
        if ($result && mysqli_affected_rows($this->link)) {
            while ($data = mysqli_fetch_assoc($result))
            {
                $newData[] = $data;
            }
        }
        //返回結果集
        return $newData;
    }
    
    //exec
    function exec($sql,$isInsert = false)
    {
        $this->initOptions();
        //執行sql
        $result = mysqli_query($this->link,$sql);
        if ($result && mysqli_affected_rows($this->link)) {
            //判斷是否插入,返回對應結果
            if ($isInsert) {
                return mysqli_insert_id($this->link);
            }else{
                return mysqli_affected_rows($this->link);
            }
        }
        return false;
    }

    function __get($name)
    {
        if ($name = 'sql') {//獲取sql語句
            return $this->sql;
        }
        return false;
    }

    //insert
    //$data數組,鍵爲字段名
    function insert($data)
    {
        $data = $this->parseValue($data);

        //提取鍵值
        $keys = array_keys($data);
        $values = array_values($data);

        $sql = 'insert into %TABLE%(%FIELD%) VALUES(%VALUES%)';
        $sql = str_replace(
            ['%TABLE%','%FIELD%','%VALUES%'],
            [$this->options['table'], join(',',$keys),join(',',$values)],$sql);
        $this->sql = $sql;
        return $this->exec($sql,true);
    }

    //給字符串值添加引號
    protected function parseValue($data)
    {
        foreach ($data as $key => $value) {
            if (is_string($value)) {
                $value = "'".$value."'";
            }
            $newData[$key] = $value;
        }
        //返回處理後數組
        return $newData;
    }

    //刪除
    function delete()
    {
        $sql = 'delete from %TABLE% %WHERE%';
        $sql = str_replace(
            ['%TABLE%','%WHERE%'],
            [$this->options['table'], $this->options['where']],$sql);
        $this->sql = $sql;
        return $this->exec($sql);
    }

    //更新
    function update($data)
    {
        $data = $this->parseValue($data);

        $value = $this->parseUpdate($data);

        $sql = 'update %TABLE% set %VALUE% %WHERE%';
        $sql = str_replace(
            ['%TABLE%','%VALUE%','%WHERE%'],
            [$this->options['table'], $value,$this->options['where']],$sql);
        $this->sql = $sql;
        return $this->exec($sql);
    }
    //拼接語句
    protected function parseUpdate($data)
    {
        foreach ($data as $key => $value) {
            $newData[] = $key.'='.$value;
        }
        return join(',',$newData);
    }

    //聚合
    function max($field)
    {
        //調用封裝方法查詢

        $result = $this->field('max('.$field.') as max')->select();
        //由於查詢的是二維數組,因此給出一個下標
        return $result[0]['max'];
    }

    //析構方法,對象銷燬時被調用
    function __destruct()
    {
        mysqli_close($this->link);
    }

    //getByName  getByAge//魔術方法,調用不存在方法時激活
    function __call($name,$args)
    {
        //截取方法名
        $str = substr($name,0,5);
        //截取字段名
        $field = substr($name,5);
        if ($str == 'getBy') {//判斷方法名是否正確
            return $this->where($field.'="'.$args[0].'"')->select();
        }
        return false;
    }
}


?>

 

<?php 

return [
	'DB_HOST' => 'localhost',
	'DB_USER' => 'root',
	'DB_PWD' => '',
	'DB_NAME' => 'tt',
	'DB_CHARSET' => 'utf8',
	'DB_PREFIX' => '',
];

?>
相關文章
相關標籤/搜索