What are some best practices for handling errors and success messages in PHP applications when performing CRUD operations?

When performing CRUD operations in PHP applications, it is essential to handle errors and success messages appropriately to provide a better user experience. One best practice is to use try-catch blocks to catch any exceptions that may occur during database operations and display error messages to the user. Additionally, using session variables to store success messages can help in notifying users about the successful completion of CRUD operations.

try {
    // Perform CRUD operation here

    // Display success message
    $_SESSION['success_message'] = "Operation completed successfully";
    header("Location: index.php");
    exit();
} catch (Exception $e) {
    // Display error message
    $_SESSION['error_message'] = "An error occurred: " . $e->getMessage();
    header("Location: index.php");
    exit();
}