The correct answer is you you are not supposed to do this. Don't store the result of htmlentities()
in the database. This function is meant to be used only when you output in HTML context! You can't know for sure if the data stored in the database will always be used in HTML context.
XSS-prevention is very context-dependent. What if you would like to output to JavaScript or CSV or simply search the values in the database? You can't do it if they are encoded for HTML output.
To answer your more pressing issue I need to mention that your code is vulnerable to SQL injection. Use prepared statements with parameter binding.
The correct mysqli example of INSERT
query would be as follows:
<?php
$var = "<script>alert('hello')</script>";
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = new mysqli("localhost", "root", "", "xss");
$conn->set_charset('utf8mb4');
$stmt = $conn->prepare('INSERT INTO entities (ent) VALUES(?)');
$stmt->bind_param('s', $var);
$stmt->execute();
// use htmlentities when in HTML context
echo '<div>'.htmlentities($var).'</div>';