Question

I have this code:

if($update[$entity_id])
{
    my $sql = "UPDATE cache SET date = '?', value = '?' WHERE item_id = ? AND level = ? AND type = ?;";
}
else
{
    my $sql = "INSERT INTO cache (date, value, item_id, level, type) VALUES ('?','?',?,?,?);";
}
my $db = $self->{dbh}->prepare(q{$sql}) or die ("unable to prepare");
$db->execute(time2str("%Y-%m-%d %X", time), $stored, $entity_id, 'entity', 'variance');

But when it want to run the update I get this error:

DBD::Pg::st execute failed : called with 5 bind variables when 0 are needed.

Why?

Was it helpful?

Solution

If you had turned on strict and/or warnings, you would see what your problem is.

You're writing

if (...) {
    my $sql = ...;
} else {
    my $sql = ...;
}
execute($sql);

Which means that the $sql variables that you declare in the if branches aren't in scope and you're trying to execute completely empty SQL.

OTHER TIPS

You're preparing literal '$sql', but that is not your only problem, lexical $sql variables go out of scope outside {}.

Try,

use strict;
use warnings;
#...

my $sql;
if($update[$entity_id])
{
    $sql = "UPDATE cache SET date = ?, value = ? WHERE item_id = ? AND level = ? AND type = ?";
}
else
{
    $sql = "INSERT INTO cache (date, value, item_id, level, type) VALUES (?,?,?,?,?)";
}
my $st = $self->{dbh}->prepare($sql) or die ("unable to prepare");
$st->execute(time2str("%Y-%m-%d %X", time), $stored, $entity_id, 'entity', 'variance');
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top