Skip to content

Instantly share code, notes, and snippets.

@sstur
Created September 20, 2013 19:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sstur/6642397 to your computer and use it in GitHub Desktop.
Save sstur/6642397 to your computer and use it in GitHub Desktop.
Escape string for MySQL
function mysql_escape_string(str) {
return str.replace(/[\0\x08\x09\x1a\n\r"'\\\%]/g, function(ch) {
switch (ch) {
case "\0":
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 "\\" + ch; // prepend a backslash to double/single quotes, backslash and percent
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment