如何提高PDOException? [英] How do I raise PDOException?
问题描述
此代码工作正常,但如果有任何错误,我想要处理异常
,所以我故意在中出现语法错误查询
,但没有任何反应。以下是代码
try {
$ sql =INSERT INTO journals(topic,author,)VALUES $ topic','$ authors',');
echo1st;
$ lecturers_db-> query($ sql);
echosecond;
} catch(PDOException $ e){
echo $ e-> getMessage();
echo $ msg =Error!;
}
没有明显的语法错误,代码工作正常,但语法错误,没有任何事情发生,执行 try block
中的所有代码,并且 catch块
中的代码不会执行。
我想提出一个异常
,请问如何在这里做,谢谢任何帮助。
请确保将属性 PDO :: ATTR_ERRMODE 设置为 PDO :: ERRMODE_EXCEPTION
pre $ $ lecturers_db-> setAttribute(PDO :: ATTR_ERRMODE, PDO :: ERRMODE_EXCEPTION);
之后,任何失败的查询都会引发异常
This code works fine, but I'll want to handle exception
if any thing goes wrong, so I deliberately made a syntax error in the query
but nothing happens. Below is the code
try {
$sql = "INSERT INTO journals (topic, author, ) VALUES ('$topic', '$authors', ')";
echo "1st";
$lecturers_db->query($sql);
echo "second";
} catch(PDOException $e) {
echo $e->getMessage();
echo $msg = "Error!";
}
Without the obvious syntax error, the code works fine but with the syntax error, nothing happens, all the code in the try block
executes and the code in the catch block
never executes.
I want to raise an exception
, please how do I do it here, thanks for any help.
Be sure to set the attribute PDO::ATTR_ERRMODE to PDO::ERRMODE_EXCEPTION, as soon as you init your pdo object:
$lecturers_db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
After that, any failed queries will raise an exception
这篇关于如何提高PDOException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!