带消息'SQLSTATE [42000]的PDOException':

时间:2012-12-13 00:52:11

标签: php mysql pdo

我收到以下错误:

Fatal error: Uncaught exception 'PDOException' with message 
'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error 
in your SQL syntax;

但是,我无法解决。行号表示它是15

$res->execute(array_values($params)); 

你能发现问题吗?

function fetchBgnew(array $conditions){ 
    $db = Core::getInstance();              
    $sql = "SELECT p.id, p.bg, p.bg_desc, p.bg_id, p.user_id, p.panel_id, p.domainurl, 
                   p.type, p.price 
              FROM ".USERS_BG." as p 
              left join ".USERS." as u on p.user_id=u.id WHERE u.status !=0 and 1 and";
    $params = array();
    foreach ($conditions as $column => $value) {
        if (preg_match('/^[a-z]+$/', $column)) {
            $sql .= "$column = ?";
            $params[] = $value;
            $sql .= "group by p.id desc, LIMIT 0,25";
        }
    }                
    $res = $db->dbh->prepare($sql);
    $res->execute(array_values($params));                
    $res->fetchAll(PDO::FETCH_ASSOC);

    $sql="SELECT p.id FROM ".USERS_BG." as p 
            left join ".USERS." as u on p.user_id=u.id WHERE u.status !=0 and";
    $params = array();
    foreach ($conditions as $column => $value) {
        if (preg_match('/^[a-z]+$/', $column)) {
            $sql .= "$column = ? group by p.id desc LIMIT 0,25";
            $params[] = $value;
        }
    }
    $cnt = $db->dbh->prepare($sql);
    $cnt->execute(array_values($params));           
    $cnt->rowCount();

    return $result = array("data"=>$res, "count"=>$cnt);
}
function fetchUser(array $conditions){       
    $db = Core::getInstance();
    $sql = "SELECT id FROM ruj_users_jel WHERE";
    $params = array();
    foreach ($conditions as $column => $value) {
        if (preg_match('/^[a-z]+$/', $column)) {
            $sql .= "$column = ?";
            $params[] = $value;
        }
    }

    $res = $db->dbh->prepare($sql);
    $res->execute(array_values($params));
    $numrows = $res->rowCount();

return $numrows;


}
$bgdataarr = fetchBgnew(array("p.status"=>'1'));

$bgdata = $bgdataarr['data'];

$page_title = "Home";
foreach($bgdata as $brag){
    print_r($bgdata[$i]['countjellys']=fetchUser(array('brag_id'=>$bg['id']))); 
}

2 个答案:

答案 0 :(得分:3)

看起来你忘记了这些空间。

$sql = "SELECT p.id,p.bg,p.bg_desc,p.bg_id,p.user_id, p.panel_id,p.domainurl,p.type,p.price FROM ".USERS_BG." as p left join ".USERS." as u on p.user_id=u.id WHERE u.status !=0 and 1 and";
...
$sql .= "$column = ?";
...
$sql .= "group by p.id desc, LIMIT 0,25";

这将产生类似SELECT ... andcolumn =的声明(注意'和'和'列'之间缺少空格)

此外,您的GROUP BY语法不正确(DESC之后不应该有逗号)并再次丢失空格。想象一下如果你有两个领域会发生什么?

答案 1 :(得分:1)

除了@TomvanderWoerdt的(正确...)答案之外:你的sql语句无效,你最后只能添加一个LIMIT子句。

同样适用于GROUP BY条款。