PHP8.1.21版本已发布
vue8.1.21版本已发布
jquery8.1.21版本已发布

博客列表 > php之数据库链式操作

php之数据库链式操作

月光下,遗忘黑暗
月光下,遗忘黑暗 原创
2021年05月11日 22:43:41 1095浏览

代码块

<?php/** * 事件委托 : 数据库查询构造器 * Db::table()->field()->where()->limit()->select()->toArray(); *  */ //被委托的类class Query{    protected $db;//pdo连接对象    protected $table;    protected $field;    protected $limit;    protected $value;    //连接数据库    private function connect($dsn,$username,$password)    {        $this->db = new PDO($dsn,$username,$password);    }    function __construct($dsn,$username,$password)    {        $this->connect($dsn,$username,$password);    }    //数据表方法    public function table($table)    {        $this->table = $table;        return $this;    }    public function field($field)    {        $this->field = $field;        return $this;    }    public function limit($limit)    {        $this->limit = $limit;        return $this;    }    public function value($value)    {        $this->value = $value;        return $this;    }    public function getSql()    {        return sprintf('INSERT INTO %s (%s) VALUE(%s)',$this->table,$this->field,$this->value);    }    //执行查询    public function select()    {        return $this->db->query($this->getSql())->fetchAll(PDO::FETCH_ASSOC);    }    public function insert()    {         return $this->db->exec($this->getSql());     }}//工作类class Db{    static function __callStatic($method,$args)    {        $dsn = 'mysql:host=localhost;dbname=video';        $username = 'root';        $password = 'root';        $query = new Query($dsn,$username,$password);        //直接委托给Query类中的具体方法完成        return call_user_func([$query,$method],...$args);    }}$res = Db::table('admins')->field('username,password,truename,gid,add_time')->value("'aaa',321,'fdsaf',1,52342")->insert();echo '<pre>';print_r($res);

效果

声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议