I have gone through a variety of questions that have been asked with the same thing in mind but it doesn't seem to be working for me.
I have a HTML textarea from which I collect the comments of a user and I'm storing them in a MySql database. So I want the special characters that are entered by the users to also be accepted without any error/exception and store them in the database as well.
I came across a solution for the newline character and I added this line of code which works well.
var comment = document.getElementById("commentArea").value;
comment = comment.replace(/\n/g, '<br />');
The other characters like &$%#(
are all getting inserted without any problem except for quotes. I'm not sure what should I do to escape them.
I tried comment.replace("\'","&39")
for escaping single quotes but that doesn't seem to work.
How can I escape both single and double quotes? Thanks in advance.
EDIT: I'm using Jsp and Servlets for my application. Should I escape these characters in the servlet then?
Let me know the reason before downvoting.
Update: As suggested in the answers and comments, I used a prepared statement and passed the string using the setString()
method. However, the problem still persists.
The code snippet I've used is:
String query = "insert into db_name (column1,column2,column3,column4) values("SomeValue1","SomeValue2",?,"SomeValue3")";
st=conn.prepareStatement(query);
st.setString(1,"String_from_TextArea");
int rows = st.executeUpdate();