What are the best practices for handling database connections and queries in PHP scripts to ensure data is displayed correctly on a website?

When handling database connections and queries in PHP scripts, it is important to properly establish a connection to the database, sanitize input data to prevent SQL injection attacks, and handle errors gracefully to ensure data is displayed correctly on a website.

// Establish a connection to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

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

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

// Sanitize input data
$id = mysqli_real_escape_string($conn, $_GET['id']);

// Perform a query
$sql = "SELECT * FROM table WHERE id = $id";
$result = $conn->query($sql);

// Handle errors
if (!$result) {
    die("Error: " . $conn->error);
}

// Display data on the website
while ($row = $result->fetch_assoc()) {
    echo $row['column'];
}

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