How can proper error handling techniques improve the reliability of PHP scripts that connect to databases?

Proper error handling techniques in PHP scripts that connect to databases can improve reliability by providing detailed error messages, allowing for easier troubleshooting and debugging. By catching and handling errors gracefully, the script can prevent unexpected crashes and provide a better user experience. Additionally, error handling can help prevent sensitive information from being exposed in error messages.

<?php
// Connect to database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";

$conn = new mysqli($servername, $username, $password, $dbname);

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

// Query database
$sql = "SELECT * FROM table";
$result = $conn->query($sql);

if ($result === false) {
    die("Error executing query: " . $conn->error);
}

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

// Close connection
$conn->close();
?>