What best practices should be followed when fetching data from a MySQL database in PHP?

When fetching data from a MySQL database in PHP, it is important to use prepared statements to prevent SQL injection attacks. Additionally, it is recommended to sanitize user input to avoid any malicious code execution. Finally, always remember to close the database connection after fetching the data to free up resources.

<?php
// 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);
}

// Prepare and execute a SQL query using a prepared statement
$stmt = $conn->prepare("SELECT * FROM table WHERE column = ?");
$stmt->bind_param("s", $columnValue);

$columnValue = "some_value";
$stmt->execute();

$result = $stmt->get_result();

// Fetch data from the result set
while ($row = $result->fetch_assoc()) {
    // Process the fetched data
    echo $row['column_name'] . "<br>";
}

// Close the prepared statement and database connection
$stmt->close();
$conn->close();
?>