http://www.perlmonks.org?node_id=149630


in reply to Backslashes with DBI quote( ) and MySQL

Using placeholders has the same effect as the quote() method.
#!/usr/bin/perl -w use strict; use DBI; # change the connect statement according to your needs my $dbh = DBI->connect("DBI:mysql:test;host=localhost;" ."mysql_read_default_file=$ENV{HOME}/.my.cnf", undef,undef,{RaiseError => 1}); my @quotes = ("\\", "\\\\", "\\\\\\", "'", "''", "\\".'"', '"', "\\".'"', "'" . '"' . "'"); $dbh->do(qq{drop table if exists test_chars}); $dbh->do(qq{create table test_chars (quote char(5))}); my $sth = $dbh->prepare( qq{insert into test_chars values ( ? ) } ); for (@quotes) { $sth->execute( $_ ); } print_chars(); print "\n"; $dbh->do(qq{delete from test_chars}); for (@quotes) { my $quoted = $dbh->quote($_); $dbh->do( qq{insert into test_chars values ($quoted)}); }; print_chars(); sub print_chars { my $aref = $dbh->selectall_arrayref( qq{select * from test_chars} ); for my $row (@$aref) { for my $field(@$row) { print "<$field>\t"; } print "\n" } } $dbh->disconnect(); __END__ output: <\> <\\> <\\\> <'> <''> <\"> <"> <\"> <'"'> <\> <\\> <\\\> <'> <''> <\"> <"> <\"> <'"'>
This sample script will insert your values escaping them with placeholders. Then it repeats the same operation using the quote() method.
As you can see, the result is the same.

One more possibility would be to use a hexadecimal string, but it might be overkill. However, just in case, the method is as follows:
my $hexstr = "0x" . unpack("H*", $barestr); $dbh->do(qq{insert into test_chars values( $hexstr )}); # notice that the hexstring has NO QUOTES
As long as you can manipulate your string with Perl, you can always turn it into an hex string, solving any possible quotes problem. The drawback is that your string in the query will be twice as long as the original. It's important to bear that in mind when you calculate the size of your query.

update
Concerning the problem you mention about the special characters not being escaped in the database, it really depends on the client you are using. When you say "look into the database" you are actually asking a client to fetch some info from the server. Therefore all you see depends on the reporting capabilities of the client you are using.
Here is an example, from the standard mysql client in Linux.
mysql> select * from test_chars; +-------+ | quote | +-------+ | \ | | \\ | | \\\ | | ' | | '' | | \" | | " | | \" | | '"' | +-------+ 9 rows in set (0.00 sec)
Another client, mysqldump will escape our data:
# # Dumping data for table 'test_chars' # INSERT INTO test_chars VALUES ('\\'); INSERT INTO test_chars VALUES ('\\\\'); INSERT INTO test_chars VALUES ('\\\\\\'); INSERT INTO test_chars VALUES ('\''); INSERT INTO test_chars VALUES ('\'\''); INSERT INTO test_chars VALUES ('\\\"'); INSERT INTO test_chars VALUES ('\"'); INSERT INTO test_chars VALUES ('\\\"'); INSERT INTO test_chars VALUES ('\'\"\'');
HTH
_ _ _ _ (_|| | |(_|>< _|