Home > Database > Mysql Tutorial > How Can I Safely Query MySQL with JavaScript Strings in Node.js?

How Can I Safely Query MySQL with JavaScript Strings in Node.js?

Patricia Arquette
Release: 2025-01-03 19:13:42
Original
891 people have browsed it

How Can I Safely Query MySQL with JavaScript Strings in Node.js?

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;
        }
    });
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template