php连贯操作原理带数据库配置(简单原理)

<?php

class Db{

    private $localhost = null;
    private $username = null;
    private $password = null;
    private $database = null;
    private $prefix = null;
    private $charset = null;
    var $master = true;

    private $sql = array(
        "field" => "",
        "table" => "",
        "where" => "",
        "order" => "",
        "limit" => "",
        "group" => "",
        "having" => "",
    );
    //数据库参数配置
    var $conf = array(
        'localhost' => 'localhost',//localhost
        'username' => 'root',//用户名
        'password' => 'root',//密码
        'database' => 'test',//数据库名字
        'prefix' => '',//数据表前缀
        'charset' => 'utf8',//字符编码
    );

    //默认链接数据库
    public function __construct(){

        $this->localhost = $this->conf['localhost'];
        $this->username = $this->conf['username'];
        $this->password = $this->conf['password'];
        $this->database = $this->conf['database'];
        $this->prefix = $this->conf['prefix'];
        $this->charset = $this->conf['charset'];
        $this->conn = mysqli_connect($this->localhost, $this->username, $this->password);
        mysqli_select_db($this->conn, $this->database);
        mysqli_query($this->conn, 'set names ' . $this->charset);
    }
    
    // __call()方法不存在时触发。$methodName调用的方法名,$args调用的参数(数组形式)
    function __call($methodName, $args)
    {
        // strtolower将第一个参数(代表不存在方法的方法名称),全部转成小写方式,获取方法名称  
        $methodName = strtolower($methodName);
        // 如果调用的方法名和成员属性数组$sql下标对应上,则将第二个参数给数组中下标对应的元素  
        if (array_key_exists($methodName, $this->sql)) {
            $this->sql[$methodName] = $args[0];
        } else {
            echo '调用类' . get_class($this) . '中的方法' . $methodName . '()不存在';
        }
        // 返回自己对象,则可以继续调用本对象中的方法,形成连贯操作  
        return $this;
    }
    // 连贯操作调用field() where() order() limit() group() having()方法,组合sql语句  
    // 输出连贯操作后组合输出一个sql语句,是连贯操作最后的一个方法。{}大括号表示代码块  
    function select()
    {
        $sql = "SELECT {$this->sql['field']} FROM {$this->sql['table']}
                 {$this->sql['where']} {$this->sql['order']} {$this->sql['limit']} 
                 {$this->sql['group']} {$this->sql['having']}";
        $result = mysqli_query($this->conn, $sql);
        $row = mysqli_fetch_all($result);
        return $row;
    }
}

//实例化
$db = new Db();
// 连贯操作  
$result = $db->table('t_eshop')->field('name')->limit('limit 0,10')->order('order by id desc')
    ->select();
print_r($result);
?>

  

转载于:https://www.cnblogs.com/zhangjian816/p/10299815.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值