这是我的问题,我在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);
}
答案 0 :(得分:1)
请看以下两个陈述,请告诉我,你可以告诉我它在做什么呢?
SELECT * FROM table WHERE date = ? GROUP BY car_id
get('table', array('date', '=', $date_sort), array('car_id'));
看,你试图为自己保留一两个字。 您是否真的认为有必要破坏这种节省的全部SQL体验?
摆脱这个无用的教程&#34;。它是由一些人在SQL上,PDO上都没有丝毫线索写的,特别是在OOP上。对于此查询,实际上有 nothing 面向对象。如果你想要一个查询构建器,或者你想学习如何写一个,你需要先熟悉一个现有的。取一个受欢迎的 framework 并学习如何使用其查询构建器。