42000执行预准备语句时查询中出现语法错误

时间:2012-11-27 21:33:28

标签: php mysql pdo prepared-statement

我一直在努力将我当前的脚本交换到PDO。我已经简化了这个例子的MySQL查询,但是这个版本的错误仍然存​​在。

$sql = 'SELECT * FROM :table WHERE lastUpdate > :appDate';

try{
    $db = connect();
    $stmt = $db->prepare($sql);
    $stmt->bindParam(':table', $table);
    $stmt->bindParam(':appDate', $appDate);

    foreach($tablesToCheck as $table){
        $stmt->execute();
        $resultset[] = $stmt->fetchAll();
    }
} catch(PDOException $e){
    print 'Error!: '.$e->getMessage().'<br/>';
}//End try catch

$ stmt-&gt; errorInfo()返回:

( [0] => 42000 [1] => 1064 [2] => You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the 
right syntax to use near ''GroupName' WHERE lastUpdate > NULL' at line 1 )

1 个答案:

答案 0 :(得分:1)

以下是迈克尔帮助的修改后的代码:

foreach($tablesToCheck as $table){
    $sql = 'SELECT *, \''.$table.'\' AS tableName FROM '.$table.' WHERE lastUpdate > :appDate';

    try{
        $db = connect();
        $stmt = $db->prepare($sql);
        $stmt->bindParam(':appDate', $appDate);
        $stmt->execute();

        while($row = $stmt->fetch(PDO::FETCH_ASSOC))
            $resultset[] = $row;

    } catch(PDOException $e){
        print 'Error!: '.$e->getMessage().'<br/>';
    }//End try catch
}//End foreach