How can error reporting be optimized in PHP scripts that involve MySQL queries?

To optimize error reporting in PHP scripts that involve MySQL queries, you can use the mysqli_error() function to capture and display any errors that occur during the execution of the query. By checking for errors after each query, you can quickly identify and address any issues that may arise.

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

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

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

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

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

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