我无法使用GROUP BY
,ORDER BY
,LIMIT
,一般来说我的查询工作正常但是当我尝试更具体时,我会遇到问题。我试图将其分解并逐步进行,但我无法弄清楚问题。
从我的用户类,我这样称呼DB:
$this->_db->get('listings', array('userid', '=', $this->data()->id, ' AND ',
'email', ' = ', $this->data()->email, ' GROUP BY reference ORDER BY row ASC'));
我的 DB 类设置如下:
public function get($table, $where){return $this->action('SELECT * ', $table, $where);}
private function action($action, $table, $where = array()){
$operators = array('=', '>', '<', '>=', '<=' , 'AND' ,'OR', 'LIKE', 'GROUP BY','ORDER BY', 'ASC', 'DESC');
if(!empty($where)){
$sql = "{$action} FROM {$table} WHERE ";
if(count($where) > 3){
$sql .= "(";
$isOp = FALSE;
foreach ($where as $key => $value) {
if($isOp){
if(in_array($value, $operators)){
$sql .= " {$value} ";
$isOp = FALSE;
}else{return FALSE;}
}else{
$sql .= " {$value} ";
$isOp = TRUE;
}
}
$sql .= ")";
if(!$this->query($sql, array($value))->error()){return $this;}
}else if(count($where) === 3){
$field = $where[0];
$operator = $where[1];
$value = $where[2];
if(in_array($operator, $operators)){
$sql = "{$action} FROM {$table} WHERE {$field} {$operator} ?"; // NO $value ?
if(!$this->query($sql, array($value))->error()){return $this;}
}
}
}else{
// If array is empty
$sql = "{$action} FROM {$table}";
if(!$this->query($sql)->error()){return $this;}
}
return FALSE;
}
public function query($sql, $params = array()){
$this->_error = FALSE;
if($this->_query = $this->_pdo->prepare($sql)){
$x = 1;
if(count($params)){
foreach($params as $param){
$this->_query->bindValue($x, $param);
$x++;
}
}// End IF count
if($this->_query->execute()){
$this->_lastID = $this->_pdo->lastInsertId();
try{
$this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
}catch(Exception $e){
// Catch Error
}
$this->_count = $this->_query->rowCount();
}else{$this->_error = TRUE;}
}
return $this;
}
总的来说,我正在通过阅读教程和遵循书中的说明从头开始构建所有内容。
我再次遇到以下Group By,Order By,Like,Limit ..我可能没有正确绑定它但是我没有足够的知识来找到我的错误。
提前致谢。
错误我获取
SELECT * FROM listing WHERE(userid = 4 GROUP BY reference)异常'PDOException',消息'SQLSTATE [42000]:语法错误或访问冲突:1064 SQL语法错误;查看与您的MySQL服务器版本对应的手册,以便在第1行的“GROUP BY参考”附近使用正确的语法
答案 0 :(得分:0)
我会在你的代码(DB类)中删除de():
$sql .= "(";
$sql .= ")";
GROUP BY不应该在WHERE的()部分。
WHERE(userid = 4 GROUP BY引用)
必须:
WHERE ( userid = 4 ) GROUP BY reference;
或更好:
WHERE userid = 4 GROUP BY reference;
在SELECT中使用SUM,COUNT等时,可以使用GROUP BY函数。否则你不需要它。