【问题标题】:42000 Syntax error in query when executing prepared statement42000 执行准备好的语句时查询中的语法错误
【发布时间】:2012-11-27 21:33:27
【问题描述】:

我一直在努力将我当前的脚本换成 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->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 )

【问题讨论】:

  • 您不能在准备好的语句中使用占位符作为表或列标识符。 :table 因此在那里无效。
  • 相反,对照白名单可接受值列表检查$table 的输入值,并将其连接到查询中。
  • 我想我可以在 foreach 中使用 try-catch 并在查询中使用 $table 。但是谢谢你,我不知道你不能使用表格或列占位符

标签: php mysql pdo prepared-statement


【解决方案1】:

这是在 Michael 的帮助下修改后的代码:

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

【讨论】:

    猜你喜欢
    • 2014-06-18
    • 1970-01-01
    • 1970-01-01
    • 2013-06-12
    • 2020-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多