在PHP中扩展GROUP BY查询到现有的PDO get查询


Expanding GROUP BY query into existing PDO get query in PHP

这是我的问题,我遵循youtube上使用PDO作为查询的教程,更像是面向对象的php查询。我试着扩展get()函数的功能。其中主要的get()action是对仅能得到参数WHERE的函数的扩展。下面是代码:

public function action($action, $table, $where = array()) {
    if (count($where) === 3) { // make sure 3 array
        $operators = array('=', '>', '<', '>=', '<='); // available operators
        $field      = $where[0];
        $operator       = $where[1];
        $value      = $where[2];
        if(in_array($operator, $operators)) {
            $sql = "{$action} FROM {$table} WHERE {$field} {$operator} ?";
            if (!$this->query($sql, array($value))->error()) {
                return $this;
            }
        }
    }
    return false;
}
public function get($table, $where) {
    return $this->action('SELECT *', $table, $where);
}

我试图在这个函数中扩展GROUP BY查询。这是我到目前为止的尝试。但是我在 count()

页面上出现了这个错误

Fatal error: Call to a member function count() on a non-object在此函数

// Find user and return first found
public function find($user = null) {
    if ($user) {
        $field = (is_numeric($user)) ? 'user_id' : 'username';
        $data = $this->_db->get('user', array($field, '=', $user));
        **if ($data->count()) {**
            $this->_data = $data->first();
            return true;
        }
    }
    return false;
}

我正在执行的查询:

DB::getInstance()->get('table', array('date', '=', $date_sort), array('car_id'));

到目前为止我所做的是:

public function action($action, $table, $where = array(), $group = array()) {
    if (count($where) === 3) { // make sure 3 array
        $operators = array('=', '>', '<', '>=', '<='); // available operators
        $field      = $where[0];
        $operator   = $where[1];
        $value      = $where[2];
        $g_field    = $group[0];
        if(in_array($operator, $operators)) {
            $sql = "{$action} FROM {$table} WHERE {$field} {$operator} ? GROUP BY {$g_field}";
            if (!$this->query($sql, array($value))->error()) {
                return $this;
            }
        }
    }
    return false;
}
//$user = DB::getInstance()->get('user', array('username', '=', 'sanbrons'));
public function get($table, $where, $group = null) {
    return $this->action('SELECT *', $table, $where, $group);
}

看下面两个语句,请告诉我,哪一个你能看出它到底在做什么?

SELECT * FROM table WHERE date = ? GROUP BY car_id
get('table', array('date', '=', $date_sort), array('car_id'));

看,你在试图为自己节省一两个字。你真的认为值得为了这样的节省而破坏整个SQL体验吗?

删掉这个无用的"教程"。它是由一个对SQL, PDO,特别是OOP都没有丝毫了解的人写的。这个查询实际上没有任何面向对象的内容。如果您想要一个查询构建器,或者如果您想学习如何编写一个,您需要首先熟悉现有的为自己获取一个流行的框架并学习如何使用它的查询生成器