What is the best practice for dynamically filling input fields with data from a database using PHP?

When dynamically filling input fields with data from a database using PHP, the best practice is to first retrieve the data from the database, then populate the input fields with the retrieved data. This can be done by using PHP to query the database, fetch the data, and then echo the data into the value attribute of the input fields.

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

// Query database to retrieve data
$sql = "SELECT * FROM table_name WHERE id = 1";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // Output data into input fields
    while($row = $result->fetch_assoc()) {
        $field1 = $row['field1'];
        $field2 = $row['field2'];
    }
} else {
    echo "0 results";
}

$conn->close();
?>

<form>
    <input type="text" name="field1" value="<?php echo $field1; ?>">
    <input type="text" name="field2" value="<?php echo $field2; ?>">
</form>