What best practices should be followed when fetching and displaying data from a SQL query in a PHP script?

When fetching and displaying data from a SQL query in a PHP script, it is important to use prepared statements to prevent SQL injection attacks. Additionally, it is recommended to sanitize and validate user input before executing the query to ensure data integrity. Finally, properly handle errors and exceptions to provide a secure and reliable application.

// Establish a database connection
$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 SQL query
$stmt = $conn->prepare("SELECT * FROM table WHERE column = ?");
$stmt->bind_param("s", $columnValue);
$columnValue = $_POST['input'];
$stmt->execute();

// Fetch and display results
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    echo "Column: " . $row['column'] . "<br>";
}

// Close statement and connection
$stmt->close();
$conn->close();