What is the best practice for handling special characters and preventing HTML injection when displaying database values in HTML form fields using PHP?

Special characters in database values can potentially be used for HTML injection attacks if not properly handled. To prevent this, it is recommended to use the htmlspecialchars() function in PHP when displaying database values in HTML form fields. This function will convert special characters like <, >, and & into their respective HTML entities, rendering them harmless.

&lt;?php
// Assuming $value contains the database value to be displayed in an HTML form field
echo &#039;&lt;input type=&quot;text&quot; name=&quot;field_name&quot; value=&quot;&#039; . htmlspecialchars($value) . &#039;&quot;&gt;&#039;;
?&gt;