Question

Hoping for some help on this one as it is far to early in the morning and my brain is not in full working condition as of yet.

The following SQL statement is valid and gives the desired output, but when used in my perl script it returns the error below.

 my $stmt = 'SELECT DATE_FORMAT(completion_time, '%m') as 'month', COUNT(id) as 'total' FROM calls WHERE DATE_FORMAT(completion_time, '%Y') = ? GROUP BY DATE_FORMAT(completion_time, '%m')';
 my $sth = database->prepare($stmt);
 $sth->execute(params->{year});

Error

Uncaught exception from user code:
        Unmatched ) in regex; marked by <-- HERE in m/) <-- HERE  as / at /home/dev/Dancer/lib/new.pm line 507.
Compilation failed in require at ./bin/app.pl line 4.

I am using Dancer and it's Database Plugin but that is working perfectly everywhere else in the app so it is definitely an issue with my syntax or my usage of DATE_FORMAT, but I am not sure as I have not used DATE_FORMAT prior to today.

As always any help is appreciated and thank you in advance.

Was it helpful?

Solution

Looks like your quoting is messed up.

Try something like this:

my $stmt = "SELECT DATE_FORMAT(completion_time, '%m') as 'month', ".
           "COUNT(id) as 'total' FROM calls WHERE ".
           "DATE_FORMAT(completion_time, '%Y') = ? ".
           "GROUP BY DATE_FORMAT(completion_time, '%m')";

OTHER TIPS

As has already been pointed out, it's your quoting. However, instead of using double quotes "" as an alternate form of string encapsulation, I'd suggest that you use q{} so that your sql is still single quoted:

my $stmt = q{SELECT DATE_FORMAT(completion_time, '%m') as 'month', COUNT(id) as 'total' FROM calls WHERE DATE_FORMAT(completion_time, '%Y') = ? GROUP BY DATE_FORMAT(completion_time, '%m')};
my $sth = database->prepare($stmt);
$sth->execute(params->{year});

This is a much better technique to fall back to. This is also true for double quoted strings by using qq{}. It's fairly common to have mixed single and double quotes in an html string, so as long as your braces are balanced (which they will be 99% of the time), then this avoids having to switch back and forth.

The Problem is very simple. You use single Quotes for the query and for the quoting inside the String.

my $stmt = "SELECT DATE_FORMAT(completion_time, '%m') as 'month', COUNT(id) as 'total' FROM calls WHERE DATE_FORMAT(completion_time, '%Y') = ? GROUP BY DATE_FORMAT(completion_time, '%m')";
my $sth = database->prepare($stmt);
$sth->execute(params->{year});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top