Making JavaScript Strings MySQL-Friendly
When attempting to pass a JavaScript string containing an email address to a NodeJS server for query execution in a MySQL database, users may encounter issues. While regular text, such as usernames, is handled without complications, email addresses face difficulties due to special characters that may require escaping for SQL compatibility.
To address this issue, an alternative to the escape function is sought, paralleling the functionality of PHP's mysql_real_escape_string(). This function protects against SQL injections by escaping specific characters.
A JavaScript implementation of mysql_real_escape_string() is surprisingly straightforward, as observed in the provided documentation. Here's the implementation:
function mysql_real_escape_string(str) { return str.replace(/[\x08\x09\x1a\n\r"'\\%]/g, function (char) { switch (char) { case "": return "\0"; case "\x08": return "\b"; case "\x09": return "\t"; case "\x1a": return "\z"; case "\n": return "\n"; case "\r": return "\r"; case "\"": case "'": case "\": case "%": return "\" + char; // prepends a backslash to backslash, percent, // and double/single quotes default: return char; } }); }
Note that this implementation goes beyond the PHP original by escaping additional characters, such as tabs, backspaces, and '%', making it suitable for LIKE queries as well.
Although mysql_real_escape_string() is character-set-aware in its PHP counterpart, the benefits of this feature in the JavaScript implementation are unclear.
Further discussions on this topic can be found at the provided link for reference.
The above is the detailed content of How to Safely Escape JavaScript Strings for MySQL Queries?. For more information, please follow other related articles on the PHP Chinese website!