What are the best practices for handling errors and debugging MySQL queries in PHP?

When handling errors and debugging MySQL queries in PHP, it is important to enable error reporting, use try-catch blocks to catch exceptions, and utilize functions like mysqli_error() to retrieve detailed error messages. Additionally, using prepared statements can help prevent SQL injection attacks and make debugging easier.

// Enable error reporting
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

// Connect to MySQL database
$mysqli = new mysqli("localhost", "username", "password", "database");

// Use try-catch block to catch exceptions
try {
    // Perform MySQL query
    $result = $mysqli->query("SELECT * FROM users");
    
    // Check for errors
    if (!$result) {
        throw new Exception($mysqli->error);
    }
    
    // Fetch results
    while ($row = $result->fetch_assoc()) {
        // Process data
    }
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}

// Close connection
$mysqli->close();