Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

DBI mysql substring_index syntax error

by Rodster001 (Pilgrim)
on Oct 22, 2014 at 04:08 UTC ( [id://1104629]=perlquestion: print w/replies, xml ) Need Help??

Rodster001 has asked for the wisdom of the Perl Monks concerning the following question:

This statement works fine from the mysql prompt:
  SELECT DISTINCT SUBSTRING_INDEX(SUBSTRING_INDEX(path, "\\", -2), "\\", 1) AS dir FROM files
But I get a "DBD::mysql::st execute failed" error when I run this:
my $query = qq~ SELECT DISTINCT SUBSTRING_INDEX(SUBSTRING_INDEX(path, "\\", -2), "\\ +", 1) AS dir FROM files ~; my $sth = $dbh->prepare($query); my $rv = $sth->execute;
DBD::mysql::st execute failed: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '\", 1) AS dir

So, I believe that something is not escaped properly in my statement and I have tried several different ways but no luck.

Any ideas?

Replies are listed 'Best First'.
Re: DBI mysql substring_index syntax error
by Loops (Curate) on Oct 22, 2014 at 04:16 UTC

    If you print the string out you'll see it has been modified and no longer matches what you're using in MySql, instead:

    my $query = 'SELECT DISTINCT SUBSTRING_INDEX(SUBSTRING_INDEX(path, "\\ +\\", -2), "\\\\", 1) AS dir FROM files';
      Got it, changed to:
      SELECT DISTINCT SUBSTRING_INDEX(SUBSTRING_INDEX(i.path, '\\\\', -2) , '\\\\', 1) AS dir
      
      Thanks!
Re: DBI mysql substring_index syntax error
by FloydATC (Deacon) on Oct 22, 2014 at 04:47 UTC

    Use placeholders whenever possible, use ->quote() everywhere else.

    This would take care of all escaping issues for you, and make you invulnerable against SQL injection attacks.

    -- FloydATC

    Time flies when you don't know what you're doing

      But, there are no variables in this query :) I agree with you, I always use placeholders.
        Yes, which means that you don't need interpolation and that you could use a differfent quoting mechanism.

        I can't test it, but using q instead of qq with your original string should probably be sufficient. Or you could possibly use the quotemeta function to get the escaping right.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://1104629]
Approved by Loops
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others cooling their heels in the Monastery: (6)
As of 2024-04-23 07:43 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found