Apply specialchars only to the final rendered sql string

htmlspecialchars() is being applied too many times here.

I couldn't pull request to the develop branch since L4 is in there.