When developing web applications, database query operations are frequently used. However, when interacting with databases using PHP’s PDO, many beginners simply return a generic “Query failed” message when a query fails. This does not provide a clear problem description or any effective information for subsequent processing.
To enhance user experience and system robustness, we can use PDO::errorCode in combination with PDOStatement::fetch to make more detailed judgments about the query results and provide more user-friendly error messages.
Suppose we are developing a feature to query user information, using PDO for database operations:
<?php
try {
$pdo = new PDO('mysql:host=localhost;dbname=test', 'user', 'password');
$stmt = $pdo->prepare('SELECT * FROM users WHERE id = :id');
$stmt->execute(['id' => $_GET['id']]);
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if ($stmt->errorCode() !== '00000') {
// SQL execution error
error_log('Database error code: ' . $stmt->errorCode());
echo 'The system is busy, please try again later.';
} elseif (!$result) {
// Query succeeded but no results
echo 'No user information found.';
} else {
// Query succeeded and there are results
echo 'Username: ' . htmlspecialchars($result['username']);
}
} catch (PDOException $e) {
// Catch connection errors or SQL syntax errors
error_log('PDO exception: ' . $e->getMessage());
echo 'A system error occurred, please contact the administrator (m66.net).';
}
?>
In the example above, we use fetch to retrieve the query result, and we use errorCode to determine if there are any SQL errors. This approach offers several advantages:
Distinguishing error types: We can clearly identify whether the SQL execution failed (e.g., due to syntax errors or missing fields) or if the query succeeded but returned no results (e.g., the WHERE condition did not match).
More detailed logging: Logging error codes or exception details helps to quickly locate problems.
More user-friendly messages: Returning clear messages to users instead of simply saying “An error occurred.”
For larger projects, it is recommended to encapsulate error handling into a reusable function. For example:
function handleQuery(PDOStatement $stmt) {
if ($stmt->errorCode() !== '00000') {
error_log('SQL error [' . $stmt->errorCode() . ']: ' . implode(', ', $stmt->errorInfo()));
return ['error' => 'Database query failed, please try again later (m66.net)'];
}
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$result) {
return ['error' => 'No related records found'];
}
<p>return ['data' => $result];<br>
}
Then, call this function to handle the results in the actual code:
$stmt = $pdo->prepare('SELECT * FROM posts WHERE id = :id');
$stmt->execute(['id' => $postId]);
$response = handleQuery($stmt);
if (isset($response['error'])) {
echo $response['error'];
} else {
echo 'Post title: ' . htmlspecialchars($response['data']['title']);
}
In practical development, properly using PDO::errorCode and fetch not only helps us identify and handle errors, but also improves the stability and user experience of the application. For users, a clear error message is far more trustworthy than a blank page or a vague “An error occurred” message. For developers, precise error information is also key to debugging and optimizing the system.
Improving the user experience starts with small details. Don't overlook those “query failed” messages anymore!
Related Tags:
PDO errorCode PDOStatement