您的 SQL 语法有误;检查与您的MySQL服务器版本相对应的手册,了解在“?”附近使用的正确语法


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 '?'

当我执行这段代码时:

$db = new Database();
$statement = $db->prepare("SHOW TABLES LIKE :table");            
if(!$statement)
    throw New Exception($db->errorInfo()[2]);
foreach($tables as $table){
    $statement->execute(array(':table' => $table));
    if($statement->rowCount() == 0)
        echo 'Table ' . $table . ' doesn''t exist';
}

我收到以下错误:

Exception: 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 '?' at line 1 in something.php on line 4

当我像这样将单引号括起来时,不会抛出:table错误:$statement = $db->prepare("SHOW TABLES LIKE ':table'"); - 但我认为您不应该在准备好的语句中的参数周围加上单引号?
此外,我将此属性设置为数据库:$db->setAttribute(PDO::ATTR_EMULATE_PREPARES,false); ,以便在查询中使用错误语法时$statement为 false,因此我可以抛出异常。当PDO::ATTR_EMULATE_PREPARES设置为 true 时,可以执行查询。

我的问题是:使用预准备语句时,如何检查查询中的错误PDO?为什么我会收到语法错误?

您需要使用

PDO::ATTR_EMULATE_PREPARES 选项,因为本机预准备语句只能在允许表达式的情况下使用占位符。 SHOW TABLES LIKE需要文本字符串,而不是表达式,因此不能在此处使用本机占位符。所以把它放在你的代码之前:

$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
相关文章: