What are some best practices for displaying data from a database in a form using PHP?

When displaying data from a database in a form using PHP, it is important to sanitize the data to prevent SQL injection attacks and to properly format the data for display. One best practice is to use prepared statements to interact with the database to prevent SQL injection. Another best practice is to loop through the database results and display them in the form fields.

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

// Retrieve data from the database
$sql = "SELECT * FROM table";
$result = $conn->query($sql);

// Display data in form fields
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo '<input type="text" name="field1" value="' . $row["field1"] . '"><br>';
        echo '<input type="text" name="field2" value="' . $row["field2"] . '"><br>';
        // Add more form fields as needed
    }
} else {
    echo "0 results";
}

$conn->close();
?>