Lecture Notes On Class 18: Working with Databases -
Part 4
Objective:
- Learn error handling
techniques in database operations.
- Use PHP functions to
manage and troubleshoot database errors.
Outcome:
Students will be able to handle and
debug database errors effectively using built-in error handling functions.
1. Introduction to Error Handling
in Database Operations
When working with databases in PHP,
it's crucial to implement error handling techniques to manage potential issues
that may arise during database interactions. Proper error handling helps
maintain the integrity of your application and provides meaningful feedback for
debugging.
Why is Error Handling Important?
- Prevent Application
Crashes: Without error handling, unexpected database errors can crash
your application.
- Debugging:
Helps identify the source of the problem and facilitates easier
troubleshooting.
- User Experience:
Allows developers to provide users with informative error messages instead
of generic failure notices.
2. Common Database Errors
Some common database errors include:
- Connection Errors:
Issues connecting to the database (e.g., wrong credentials).
- Query Errors:
Problems executing SQL queries (e.g., syntax errors, missing tables).
- Data Errors:
Inconsistencies in data (e.g., inserting NULL into a NOT NULL column).
3. Error Handling Techniques in PHP
3.1. Error Reporting in PHP
Before diving into database-specific
error handling, ensure that PHP is set to report errors. You can do this by
adding the following lines at the beginning of your PHP script:
php
Copy code
error_reporting(E_ALL);
ini_set('display_errors', 1);
This will display all errors,
warnings, and notices during development.
3.2. Using Try-Catch Blocks
PHP supports exception handling using
try-catch blocks. This allows you to catch errors and handle them gracefully.
Example:
php
Copy code
try {
// Create a new PDO instance
$pdo = new PDO('mysql:host=localhost;dbname=testdb', 'username', 'password');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Execute a query
$stmt = $pdo->prepare('SELECT * FROM nonexistent_table');
$stmt->execute();
} catch (PDOException $e) {
// Handle the error
echo 'Database Error: ' . $e->getMessage();
}
3.3. Setting the PDO Error Mode
When using PDO (PHP Data Objects) for
database interactions, you can set the error mode to throw exceptions, which
makes it easier to manage errors.
php
Copy code
$pdo->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
3.4. Checking for Errors with
MySQLi
If you're using MySQLi, you can check
for errors after executing a query.
Example:
php
Copy code
$mysqli = new mysqli('localhost', 'username',
'password', 'testdb');
// Check connection
if ($mysqli->connect_error) {
die('Connection Error: ' . $mysqli->connect_error);
}
// Execute a query
$result = $mysqli->query('SELECT *
FROM nonexistent_table');
if (!$result) {
echo 'Query Error: ' . $mysqli->error;
}
4. Using Error Handling Functions
4.1. mysqli_connect_error()
This function returns a string
description of the last connection error.
php
Copy code
$mysqli = new mysqli('localhost', 'username',
'password', 'testdb');
if ($mysqli->connect_error) {
echo 'Connection Error: ' . mysqli_connect_error();
}
4.2. mysqli_error()
This function retrieves the last error
message for the specified connection.
php
Copy code
$result = $mysqli->query('SELECT *
FROM nonexistent_table');
if (!$result) {
echo 'Query Error: ' . mysqli_error($mysqli);
}
4.3. Custom Error Handling Function
You can create a custom error handling
function to centralize error reporting.
php
Copy code
function handleError($error) {
echo 'Error occurred: ' . $error;
}
// Example usage
$result = $mysqli->query('SELECT *
FROM nonexistent_table');
if (!$result) {
handleError(mysqli_error($mysqli));
}
5. Summary
In this class, we learned the
importance of error handling in database operations and explored various
techniques to manage and troubleshoot errors effectively using PHP functions.
By implementing these practices, you can enhance the reliability and maintainability
of your database-driven applications.
Key Takeaways:
- Always enable error
reporting during development.
- Utilize try-catch
blocks for exception handling.
- Set appropriate error
modes for PDO and check errors in MySQLi.
- Create custom
functions for consistent error handling.
Next Class:
In the next class, we will explore
database transactions and how to implement rollback operations to maintain data
integrity.
Homework:
- Implement error
handling in your previous database project using the techniques discussed
in class.
- Write a brief report
on how error handling improved your application’s robustness.