What best practices should be followed when using MySQL queries in PHP to prevent unexpected behavior like exiting the script prematurely?

When using MySQL queries in PHP, it's important to handle potential errors properly to prevent unexpected behavior like exiting the script prematurely. One way to achieve this is by using try-catch blocks to catch any exceptions thrown by the MySQL query execution and handle them gracefully.

try {
    $conn = new mysqli($servername, $username, $password, $dbname);
    
    if ($conn->connect_error) {
        throw new Exception("Connection failed: " . $conn->connect_error);
    }
    
    $sql = "SELECT * FROM table";
    $result = $conn->query($sql);
    
    if ($result === false) {
        throw new Exception("Error executing query: " . $conn->error);
    }
    
    // Process the query result here
    
    $conn->close();
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}