NodeJS Querying MySQL with JavaScript Strings
When attempting to pass JavaScript strings containing email addresses to NodeJS servers for MySQL database queries, developers may encounter difficulties due to the presence of special characters. To ensure proper handling of these strings, it is crucial to adapt them for SQL compatibility.
In PHP, the function mysql_real_escape_string() provides a solution by adding backslashes before specific characters such as x00, n, r, , ', " and x1a. This prevents these characters from causing issues within SQL queries.
For NodeJS, a similar functionality can be implemented as follows:
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; } }); }
This function replaces special characters with escaped versions, ensuring compatibility with SQL queries. Note that this solution also escapes tabs, backspaces, and '%' characters, making it suitable for LIKE queries as well.
For more information on SQL string escaping, refer to the discussion at [OWASP](https://owasp.org/www-community/vulnerabilities/Unrestricted_File_Upload).
The above is the detailed content of How Can I Safely Query MySQL with JavaScript Strings in Node.js?. For more information, please follow other related articles on the PHP Chinese website!