What best practices should be followed when using PHP to retrieve and display data from a database in real-time?

When using PHP to retrieve and display data from a database in real-time, it is important to follow best practices to ensure security, efficiency, and maintainability. This includes using prepared statements to prevent SQL injection attacks, sanitizing user input, validating data before displaying it, and closing database connections after use.

// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

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

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

// Retrieve and display data
$sql = "SELECT * FROM table";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo "ID: " . $row["id"] . " - Name: " . $row["name"] . "<br>";
    }
} else {
    echo "0 results";
}

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