This question already has an answer here:
这个问题在这里已有答案:
- My PDO Statement doesn't work 1 answer
- 我的PDO声明不起作用1回答
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 False
on failure, I threw together this repugnant hack:
我正在尝试使用PDO预处理语句为MySQL数据库上的查询创建正确的错误处理。我希望程序在检测到预准备语句进程中的错误时退出。利用PDO预处理语句过程中的每个步骤在失败时返回False这一事实,我把这个令人反感的黑客扔到了一起:
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 $result
assignment without returning false
on 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结果,而不会在运行checkSuccess()的任何函数上返回false。那么也许我根本不需要检查上面的逻辑呢?请记住,我在程序的早期检查数据库连接是否成功。
2 个解决方案
#1
13
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
如果我正在运行多个查询,请告诉我问题出在哪里
#2
4
You have to catch PDOException
:
你必须捕获PDOException:
try {
//your code/query
} catch (PDOException $e) {
//Do your error handling here
$message = $e->getMessage();
}
PDOException
#1
13
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
如果我正在运行多个查询,请告诉我问题出在哪里
#2
4
You have to catch PDOException
:
你必须捕获PDOException:
try {
//your code/query
} catch (PDOException $e) {
//Do your error handling here
$message = $e->getMessage();
}
PDOException