How can error reporting in PHP be optimized to troubleshoot issues related to MySQL queries and database connections?
To optimize error reporting in PHP for troubleshooting MySQL queries and database connections, you can enable error reporting, set error handling for database connections, and use try-catch blocks to catch and handle exceptions that may occur during database operations.
// Enable error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);
// Set error handling for database connections
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
// Example MySQL query
try {
$conn = new mysqli($servername, $username, $password, $dbname);
$result = $conn->query("SELECT * FROM table");
if ($result) {
while ($row = $result->fetch_assoc()) {
// Process data
}
} else {
throw new Exception("Error executing query: " . $conn->error);
}
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}