php PDO 准备语句的错误检查
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15275689/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Error Checking for PDO Prepared Statements
提问by user1427661
I'm trying to create proper error handling for queries on a MySQL database using PDO prepared statements. I want the program to exit the moment an error in the prepared statement process is detected. Taking advantage of the fact that each step in the PDO prepared statement process returns Falseon failure, I threw together this repugnant hack:
我正在尝试使用 PDO 准备好的语句为 MySQL 数据库上的查询创建正确的错误处理。我希望程序在检测到准备好的语句过程中出现错误时退出。利用 PDO 准备好的语句过程中的每一步都会False在失败时返回这一事实,我将这个令人反感的 hack 放在一起:
global $allFields;
global $db;
global $app;
//dynamically append all relevant fields to query using $allFields global
$selectQuery = 'SELECT ' . implode($allFields, ', ') .
' FROM People WHERE ' . $fieldName . ' = :value';
//prepared statement -- returns boolean false if failure running query; run success check
$success = $selectQueryResult = $db->prepare($selectQuery);
checkSuccess($success);
$success = $selectQueryResult->bindParam(':value', $fieldValue, PDO::PARAM_STR);
checkSuccess($success);
$success = $selectQueryResult->execute();
checkSuccess($success);
with checkSuccess()doing the following:
与checkSuccess()执行以下操作:
function checkSuccess($success) {
if ($success == false) {
//TODO: custom error page.
echo "Error connecting to database with this query.";
die();
}
}
Two things. First, this is horribly verbose and stupid. There must be a better way. Obviously I could store the booleans in an array or something to take out a line or 2 of code, but still.
两件事情。首先,这是非常冗长和愚蠢的。一定会有更好的办法。显然我可以将布尔值存储在一个数组或其他东西中以取出一行或两行代码,但仍然如此。
Second, is it even necessary to check these values, or should I just check the result after I perform this line of code:
其次,是否有必要检查这些值,或者我应该在执行这行代码后检查结果:
$result = $selectQueryResult->fetch(PDO::FETCH_ASSOC);
I already have code that does this:
我已经有了执行此操作的代码:
if ($result) { //test if query generated results
// do successful shit
}
else {
echo "404";
$app->response()->status(404); //create 404 response header if no results
As much as I try to break the prepared statement process by inserting weird, mismatched, or lengthy queries, my program always makes it to the $resultassignment without returning falseon any of the functions where I run checkSuccess(). So maybe I don't need to be checking the above logic at all? Keep in mind that I check for a successful database connection earlier in the program.
尽管我试图通过插入奇怪的、不匹配的或冗长的查询来破坏准备好的语句过程,但我的程序总是在$result不返回false我运行的任何函数的情况下进行赋值checkSuccess()。所以也许我根本不需要检查上述逻辑?请记住,我在程序的早期检查了成功的数据库连接。
回答by mishu
I preffer setting the error mode to throwing exceptions like this:
我更喜欢将错误模式设置为抛出这样的异常:
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
right after I connect to the database. So every problem will throw an PDOException So your code would be:
在我连接到数据库之后。所以每个问题都会抛出一个 PDOException 所以你的代码是:
$selectQuery = '
SELECT
' . implode($allFields, ', ') . '
FROM
People
WHERE
' . $fieldName . ' = :value
';
try
{
$selectQueryResult = $db->prepare($selectQuery);
selectQueryResult->bindParam(':value', $fieldValue);
$selectQueryResult->execute();
}
catch(PDOException $e)
{
handle_sql_errors($selectQuery, $e->getMessage());
}
where the function would be:
函数在哪里:
function handle_sql_errors($query, $error_message)
{
echo '<pre>';
echo $query;
echo '</pre>';
echo $error_message;
die;
}
In fact I am using a general function that also has something like
事实上,我正在使用一个通用函数,它也有类似的东西
$debug = debug_backtrace();
echo 'Found in ' . $debug[0]['file'] . ' on line ' . $debug[0]['line'];
to tell me where was the problem if I am running multiple queries
如果我运行多个查询,告诉我问题出在哪里
回答by Emery King
You have to catch PDOException:
你必须抓住PDOException:
try {
//your code/query
} catch (PDOException $e) {
//Do your error handling here
$message = $e->getMessage();
}

