What is the best practice for retrieving data from a database in PHP and displaying it in a text field or input field?

When retrieving data from a database in PHP and displaying it in a text field or input field, it is best practice to use prepared statements to prevent SQL injection attacks. You can fetch the data from the database using a SELECT query, and then populate the text field or input field with the fetched data.

<?php
// Establish a database connection
$pdo = new PDO('mysql:host=localhost;dbname=database', 'username', 'password');

// Prepare a SELECT query to retrieve data
$stmt = $pdo->prepare("SELECT field_name FROM table_name WHERE id = :id");

// Bind the parameter
$stmt->bindParam(':id', $id);

// Execute the query
$stmt->execute();

// Fetch the data
$data = $stmt->fetch(PDO::FETCH_ASSOC);

// Populate the text field or input field with the fetched data
echo '<input type="text" name="field_name" value="' . $data['field_name'] . '">';
?>