What is the equivalent javascript code for mysql_r开发者_开发技巧eal_escape_string()
?
Based on the PHP documentation of the method this would do roughly the same thing. The method mysql_real_escape_string in PHP is deprecated however.
function mysqlEscape(stringToEscape){
return stringToEscape
.replace("\\", "\\\\")
.replace("\'", "\\\'")
.replace("\"", "\\\"")
.replace("\n", "\\\n")
.replace("\r", "\\\r")
.replace("\x00", "\\\x00")
.replace("\x1a", "\\\x1a");
}
Unfortunately that's not exactly what mysql_real_escape_string does according to the 5.6 mysql API docs. It doesn't take into account character encodings among other things.
The above method will likely do what you're looking for even if you only use the first 2 replaces like so.
function mysqlEscape(stringToEscape){
return stringToEscape
.replace("\\", "\\\\")
.replace("\'", "\\\'");
}
According to the mysql docs.
MySQL requires only that backslash and the quote character used to quote the string in the query be escaped. mysql_real_escape_string() quotes the other characters to make them easier to read in log files
A good tip when you're looking for javascript equivalent versions of popular PHP functions is
phpjs.org
However your probably looking for the wrong functionality. mysql_real_escape_string() can only be used if a mysql database connection is active (More details about this can be read on the mysqli real_escape page. I.e mysql_real_escape_string() isn't really a PHP implementation, but more MySQL. If used without database connection it will just leave you with an empty variable.
You might have looked for a function that adds slashes and removes newlines? You can check the phpjs.org on how they implemented the add_slashes function. Removing newlines can be done with a custom replace function I guess.
Maybe explain in what environment you require this function to work in javascript, so we could push you in the right direction (i.e talk you out of using mysql_real_escape_string in javascript but provide tips on which function(s) you really need)
I've had an use case where I need to escape my own data (not from user input) in order to use it within a node.js script. I've fixed the code from @majinnaibu answer, because it was only escaping the first occurrence of the special symbol.
function mysqlEscape(stringToEscape){
if(stringToEscape == '') {
return stringToEscape;
}
return stringToEscape
.replace(/\\/g, "\\\\")
.replace(/\'/g, "\\\'")
.replace(/\"/g, "\\\"")
.replace(/\n/g, "\\\n")
.replace(/\r/g, "\\\r")
.replace(/\x00/g, "\\\x00")
.replace(/\x1a/g, "\\\x1a");
}
Hope this helps someone else.
There isn't any, because strings that come from JavaScript are still considered 'user input' and should never be inserted in your database directly. Your server-side has to do additional validation. There are functions to encode URLs and stuff like that.
What are you trying to do?
I think we can use escape() methode
精彩评论