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();
There is no need to escape anything in JavaScript, you'll not insert it directly but via some kind of server-side script (like PHP). That's place to perform such tasks. Especially that you can never trust anything that is done using JavaScript. User can modify it easily or even disable JavaScript. That shouldn't brake your site or database!
On server-side you can use prepared statements to safely insert data to database.