当我执行这段代码时:
$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);