如果执行的SQL出错,有什么更好(更快(的处理方法?
使用 PDO 的query()
方法:
$db_conn->query("some sql");
if ($db_conn->errorInfo()[2] !== NULL) {
// there is error
}
或使用prepare()
方法:
$sth=$db_conn->prepare("some sql");
$sth->execute();
if ($sth->errorInfo()[2] !== NULL) {
// there is error
}
我的意思是,当不需要关心SQL注入并且没有重复查询时。
它们在性能方面是否相同? 如果是,那么最好使用query()
变体,因为代码少一点?
您可能希望使用例外。见 http://php.net/manual/en/pdo.error-handling.php
$db_conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
然后后来:
try {
$sth=$db_conn->prepare("some sql");
$sth->execute();
} catch (PDOException $e) {
echo $e->getMessage();
}