How can error reporting be used in PHP to troubleshoot issues with SQL queries?

When troubleshooting SQL queries in PHP, error reporting can be used to identify and resolve issues. By enabling error reporting for SQL queries, any errors that occur during query execution will be displayed, providing valuable information for debugging. This can help pinpoint syntax errors, connection problems, or other issues that may be causing the query to fail.

// Enable error reporting for SQL queries
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

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

// Check for connection errors
if ($mysqli->connect_error) {
    die("Connection failed: " . $mysqli->connect_error);
}

// Execute SQL query
$query = "SELECT * FROM table_name";
$result = $mysqli->query($query);

// Check for query errors
if (!$result) {
    die("Error executing query: " . $mysqli->error);
}

// Process query results
while ($row = $result->fetch_assoc()) {
    // Do something with the data
}

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