Created
June 30, 2011 21:46
-
-
Save bugi/1057348 to your computer and use it in GitHub Desktop.
escape string for sql (mysql specific)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
sub escape4mysql { | |
# | |
# If you MUST construct sql, rather than use parameters via the | |
# api, you can use this function on STRINGS to avoid quote-hell sql | |
# injection attacks. | |
# | |
# One scenario is for constructing queries from spreadsheets, to be applied later in a batch. | |
# | |
# input: zero or more strings (undef is handled as null). | |
# output: same number of hex strings (or NULL). | |
my @r; | |
for my $x (@_) { | |
if( !defined $x ) { push(@r, 'NULL'); next; } | |
my $y = $x; | |
$y =~ s/(.)/sprintf("%x",ord($1))/eg; | |
push(@r, '0x'.$y); | |
} | |
return @r if wantarray ; | |
return $r[0] if @r == 1 ; | |
return 'NULL' if @r == 0 ; | |
return join(', ', @r); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment