Skip to content

Instantly share code, notes, and snippets.

@bugi
Created June 30, 2011 21:46
Show Gist options
  • Save bugi/1057348 to your computer and use it in GitHub Desktop.
Save bugi/1057348 to your computer and use it in GitHub Desktop.
escape string for sql (mysql specific)
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