Viktor Kostrov Viktor Kostrov - 9 months ago 30
PHP Question

Having issue with htmlspecialchars, where is the correct place to put it?

$stmt = $conn->prepare("INSERT INTO chatbox (username, message)
VALUES (:username, :message)");
$stmt->bindParam(':username', $username);
$stmt->bindParam(':message', $message);

$username = $_POST['username'];
$message = $_POST['message'];
$stmt->execute();
?>


Where would I put htmlspecialchars() in this situation, please help me?

Answer Source

Nowhere here. Always try to put the "raw" (see below what I mean by "raw") data into your database. Only use htmlspecialchars when you want to show the data from your database.

"raw" as in sanitized and safe for the database, but not touched in a way that it is a certain format (e.g. HTML)

//edit:
So in order to use htmlspecialchars correctly, let's say you echo that message after receiving it from the database like that:

echo htmlspecialchars($message);