What are the best practices for handling errors in PHP scripts, particularly when using MySQL queries?

When handling errors in PHP scripts, especially when dealing with MySQL queries, it's important to use error handling techniques to catch and display any potential issues. One common practice is to use try-catch blocks to handle exceptions that may arise during database operations. Additionally, using functions like mysqli_error() to retrieve error messages from MySQL can help in debugging and resolving issues efficiently.

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

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

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

// Perform MySQL query
$sql = "SELECT * FROM users";
$result = $conn->query($sql);

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

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