How can the misuse of htmlentities and mysqli_real_escape_string functions in PHP scripts lead to data corruption?

The misuse of htmlentities and mysqli_real_escape_string functions in PHP scripts can lead to data corruption by either not properly sanitizing input data or by double-escaping data, causing unintended characters to be stored in the database. To prevent data corruption, it is important to use htmlentities for output escaping and mysqli_real_escape_string for input sanitization separately and in the correct context.

// Correct usage of htmlentities for output escaping
$output = htmlentities($input, ENT_QUOTES, 'UTF-8');

// Correct usage of mysqli_real_escape_string for input sanitization
$input = mysqli_real_escape_string($connection, $input);