Error Reporting and Handling

Error Reporting and Handling in MySQLi
When working with MySQL databases in PHP, robust error handling is essential for ensuring that your applications run smoothly and for debugging issues when they arise. The MySQL Improved (MySQLi) extension provides an object-oriented interface that includes sophisticated error reporting and handling mechanisms.
This article delves into the various methods and best practices for error reporting and handling in MySQLi using an object-oriented approach, complete with code examples to illustrate these concepts.

Importance of Error Handling

Effective error handling is crucial for several reasons:
  1. Debugging: Helps identify and fix bugs in the code.
  2. User Experience: Prevents application crashes and provides meaningful error messages to users.
  3. Security: Avoids exposing sensitive information through errors.
  4. Data Integrity: Ensures that the database remains in a consistent state by handling errors gracefully.

Setting Up MySQLi Connection

Before diving into error handling, let’s start by establishing a connection to a MySQL database using MySQLi in an object-oriented manner.

Code Example: Establishing a Connection

				
					<?php
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "mydatabase";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>

				
			
In the above code:
  • $servername, $username, $password, and $dbname are the parameters required to establish a connection.
  • The new mysqli function creates a new instance of the mysqli class.
  • The connect_error property checks if there is an error in the connection process.

Basic Error Handling

MySQLi provides several properties and methods for handling errors. The primary ones include error, errno, and sqlstate.

Code Example: Basic Error Handling

				
					<?php
$sql = "SELECT id, firstname, lastname FROM NonExistentTable";
$result = $conn->query($sql);

if (!$result) {
    echo "Error: " . $conn->error . "<br>";
    echo "Error Number: " . $conn->errno . "<br>";
    echo "SQLSTATE: " . $conn->sqlstate . "<br>";
} else {
    if ($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {
            echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
        }
    } else {
        echo "0 results";
    }
}
$conn->close();
?>

				
			
In this example:
  • error property returns the last error description.
  • errno property returns the last error number.
  • sqlstate property returns the SQLSTATE error code for the last error.

Using Exceptions for Error Handling

Using exceptions is a more sophisticated and flexible way to handle errors. PHP 5 and later support exceptions, and MySQLi can be configured to throw exceptions on errors.

Enabling Exception Mode

				
					<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

try {
    $conn = new mysqli($servername, $username, $password, $dbname);
    // If the connection fails, an exception will be thrown
} catch (mysqli_sql_exception $e) {
    die("Connection failed: " . $e->getMessage());
}
?>

				
			
In this code:
  • mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT) configures MySQLi to throw exceptions on errors.
  • mysqli_sql_exception is the exception class that MySQLi uses.

Code Example: Handling Exceptions

				
					<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

try {
    $conn = new mysqli($servername, $username, $password, $dbname);
    
    $sql = "SELECT id, firstname, lastname FROM MyGuests";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {
            echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
        }
    } else {
        echo "0 results";
    }
} catch (mysqli_sql_exception $e) {
    echo "Error: " . $e->getMessage();
} finally {
    $conn->close();
}
?>

				
			
In this example:
  • The try block contains the code that might throw an exception.
  • The catch block handles the exception.
  • The finally block ensures that the connection is closed, whether or not an exception occurs.

Custom Error Handling

For more advanced scenarios, you can implement custom error handling logic. This can involve logging errors to a file, displaying user-friendly messages, or sending notifications to administrators.

Code Example: Custom Error Handling

				
					<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

function customErrorHandler($errno, $errstr, $errfile, $errline) {
    $log = "Error: [$errno] $errstr - $errfile:$errline" . PHP_EOL;
    $log .= "Ending Script" . PHP_EOL;
    error_log($log, 3, 'errors.log'); // Log error to a file
    echo "An error occurred. Please try again later.";
    exit();
}

set_error_handler("customErrorHandler");

try {
    $conn = new mysqli($servername, $username, $password, $dbname);
    
    $sql = "SELECT id, firstname, lastname FROM MyGuests";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {
            echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
        }
    } else {
        echo "0 results";
    }
} catch (mysqli_sql_exception $e) {
    customErrorHandler(E_USER_ERROR, $e->getMessage(), __FILE__, __LINE__);
} finally {
    $conn->close();
}
?>

				
			
In this example:
  • customErrorHandler is a custom error handling function that logs errors to a file and displays a user-friendly message.
  • set_error_handler(“customErrorHandler”) sets the custom error handler.
  • The catch block calls the custom error handler if an exception occurs.

Transactions and Error Handling

Transactions are essential for maintaining data integrity, especially when performing multiple related operations. MySQLi’s transaction management functions (begin_transaction(), commit(), and rollback()) are useful for ensuring that a group of operations either all succeed or all fail.

Code Example: Transactions with Error Handling

				
					<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

try {
    $conn = new mysqli($servername, $username, $password, $dbname);
    $conn->begin_transaction();

    $conn->query("INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', 'john.doe@example.com')");
    $conn->query("INSERT INTO MyGuests (firstname, lastname, email) VALUES ('Jane', 'Doe', 'jane.doe@example.com')");

    $conn->commit();
    echo "New records created successfully";
} catch (mysqli_sql_exception $e) {
    $conn->rollback();
    echo "Transaction failed: " . $e->getMessage();
} finally {
    $conn->close();
}
?>

				
			
In this example:
  • begin_transaction() starts a new transaction.
  • commit() commits the current transaction.
  • rollback() rolls back the current transaction if an error occurs.

Logging Errors

Logging errors is a best practice for monitoring and debugging applications. MySQLi errors can be logged using PHP’s error_log function.

Code Example: Logging Errors

				
					<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

try {
    $conn = new mysqli($servername, $username, $password, $dbname);
    $sql = "SELECT id, firstname, lastname FROM MyGuests";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {
            echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
        }
    } else {
        echo "0 results";
    }
} catch (mysqli_sql_exception $e) {
    error_log("Error: " . $e->getMessage(), 3, 'errors.log');
    echo "An error occurred. Please try again later.";
} finally {
    $conn->close();
}
?>

				
			
In this example:
  • error_log logs the error message to a file named errors.log.

Conclusion

Error handling in MySQLi using an object-oriented approach is essential for building robust, secure, and maintainable applications. This article covered the basic and advanced techniques for error handling in MySQLi, including setting up a connection, using exceptions, implementing custom error handlers, managing transactions, and logging errors. By following these best practices and utilizing the provided code examples, you can ensure that your PHP applications handle database errors effectively, improving both the user experience and the overall stability of your applications.
Scroll to Top