PHP鏈式調用

第一種方式

<?php

/**
 * PHP 鏈式調用構造一個查詢語句
 * Class Mysql
 */
class Mysql {

    //SQL語句
    private $sql = 'SELECT';

    /**
     * 數據庫初始化
     * @param array $config 配置項
     */
    public function __construct(array $config) {
        //邏輯處理
    }

    /**
     * 查詢字段
     * @param $fields
     * @return $this
     */
    public function fields($fields) {
        $this->sql .= ' ' . $fields;
        return $this;
    }

    /**
     * 操作表
     * @param $table
     * @return $this
     */
    public function table($table) {
        $this->sql .= ' FROM ' . $table;
        return $this;
    }

    /**
     * where條件
     * @param $where
     * @return $this
     */
    public function where($where) {
        $this->sql .= ' WHERE ' . $where;
        return $this;
    }

    /**
     * 排序
     * @param $order
     * @return $this
     */
    public function order($order) {
        $this->sql .= ' ORDER BY  ' . $order;
        return $this;
    }

    /**
     * limit限制
     * @param $limit
     * @return $this
     */
    public function limit($limit) {
        $this->sql .= ' LIMIT ' . $limit;
        return $this;
    }

    /**
     * 構造SQL
     * @return string SQL語句
     */
    public function buildSql() {

        return $this->sql;
    }
}


$mysqlObj = new Mysql(array());
$retSql = $mysqlObj
    ->fields('*')
    ->table('bi_company')
    ->where("`product_id` = 'A001' AND `is_del` = '0'")
    ->order('`company_id` DESC')
    ->limit('0, 50')
    ->buildSql();

echo '生成SQL:'.$retSql;

//生成SQL:SELECT * FROM bi_company WHERE `product_id` = 'A001' AND `is_del` = '0' ORDER BY  `company_id` DESC LIMIT 0, 50
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容