Error handling on PHP page
To improve the error handling on your PHP page, you can use a combination of error reporting and proper exception handling. Here’s how you can enhance your PHP code for better error checking and handling:
Enable Error Reporting: At the beginning of your script, enable error reporting to display all errors. This is useful during development but should be turned off or set to a lower level in a production environment.
Use Try-Catch for Exception Handling: Wrap your database connection and queries in a try-catch block to handle exceptions gracefully.
Check for Errors: Always check if your operations (like database connection and query execution) are successful.
Here’s an improved version of your PHP script with enhanced error checking and handling:
<?php
include_once($_SERVER['DOCUMENT_ROOT'] . "/cmms/utils/header.php");
// Enable error reporting for development
try {
$conn = oci_connect("abc", "abc", "abc/service name");
if (!$conn) {
$e = oci_error();
throw new Exception("Connection error: " . htmlentities($e['message'], ENT_QUOTES));
}
// Check if DPT_NAME is set in $_POST
if (!isset($_POST['NAME'])) {
throw new Exception("NAME not found in POST data.");
}
$DPT_NAME = htmlspecialchars($_POST['NAME'], ENT_QUOTES, 'UTF-8');
if ($DPT_NAME == 'Parameter') {
$sql = "Your sql Query here";
}
$stmt = oci_parse($conn, $sql);
if (!$stmt) {
$e = oci_error($conn);
throw new Exception("SQL parsing error: " . htmlentities($e['message'], ENT_QUOTES));
}
oci_bind_by_name($stmt, ':NAME', $NAME);
$r = oci_execute($stmt);
if (!$r) {
$e = oci_error($stmt);
throw new Exception("SQL execution error: " . htmlentities($e['message'], ENT_QUOTES));
}
// Process the result here (not shown in the provided code)
// Close the connection
oci_close($conn);
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
// Log the error message if needed
}
?>
- Use the
set_error_handler()
function to tell PHP how to handle standard engine errors. You can make a custom error handler the default error handler for the duration of the script by usingset_error_handler("customError");
. You can also add a second parameter to specify an error level. - Create a function that can be called when an error has occurred in PHP. The function can include the following parameters:
- $error_level: A required integer that specifies the error level
- $error_message: A required parameter that specifies the message to print
- $error_file: An optional parameter that specifies the file in which the error occurred
- $error_line: An optional parameter that specifies the line number in which the error occurred
- $error_context: An optional parameter that specifies an array containing every variable and their value when an error occurred
- Use try-catch statements to handle error exceptions. A script can use multiple exceptions to check for multiple conditions.
Post a Comment
0Comments