What is the role of htmlentities() or htmlspecialchars() in preventing masking of code in a database?

When storing user input in a database, it's important to prevent code injection attacks by escaping special characters. The htmlentities() or htmlspecialchars() functions in PHP can be used to convert special characters to their HTML entities, preventing them from being interpreted as code when retrieved from the database.

// Using htmlentities() to prevent code injection when storing user input in a database
$userInput = "<script>alert('Hello!');</script>";
$escapedInput = htmlentities($userInput);

// Store $escapedInput in the database
// When retrieving the data, use htmlspecialchars() to display it safely
echo htmlspecialchars($escapedInput);