How can error reporting and SQL error handling be effectively utilized in PHP scripts?

Error reporting and SQL error handling can be effectively utilized in PHP scripts by setting the error reporting level, using try-catch blocks for exception handling, and utilizing functions like mysqli_error() to retrieve detailed error messages from SQL queries.

// Set error reporting level
error_reporting(E_ALL);
ini_set('display_errors', 1);

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

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

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

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

// Fetch results
while ($row = $result->fetch_assoc()) {
    // Process results
}

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