Blogger Information
Blog 28
fans 1
comment 0
visits 17289
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
2019.6.17作业
关超的博客
Original
709 people have browsed it

使用静态方法的重载技术, 实现一个数据库访问类,并实例演示链接调用的实现过程

<?php

require 'select.php';

class Db{
    protected static $pdo =null;

    public static function connection(){
        self::$pdo=new PDO('mysql:host=127.0.0.1;dbname=admin',root,root);
    }

    public static function  __callStatic($name, $arguments)
    {
        // TODO: Implement __callStatic() method.
        self::connection();

        $select = new Select(self::$pdo);

        return call_user_func_array([$select,$name],[$arguments[0]]);
    }
}



$users = Db::table('user')
    ->field('id,name,sex')
    ->where('id < 10')
    ->limit(5)
    ->select();

// 遍历查询结果
foreach ($users as $user) {
    print_r($user); echo '<br>';
}


<?php
class Select{
    public $pdo = null;

    public $table = '';

    public $field='';

    public $where ='';

    public $limit = 0;

    //初始化连接对象
    public function __construct($pdo)
    {
        $this->pdo=$pdo;
    }

    public function table($table){
        $this->table=$table;
        return $this;
    }

    public function field($fields){
        $this->field=$fields;
        return $this;
    }

    public function where($where)
    {
        $this->where = $where;
        return $this;
    }

    public function limit($limit)
    {
        $this->limit = $limit;
        return $this;
    }

    public function selectmethod()
    {
        $fields = empty($this->field) ? '*' : $this->field;
        $where = empty($this->where) ? '' : ' WHERE '.$this->where;
        $limit = empty($this->limit) ? '' : ' LIMIT '.$this->limit;

        // 接装SQL语句
        $sql = 'SELECT '.$fields.' FROM '.$this->table. $where . $limit;

        $stmt = $this->pdo->prepare($sql);
        $stmt->execute();
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
}

?>


Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post