4

Got a little problem in my code, the query works fine if I manually put values in. But failed if I use my variable. The code shows below

my $get_meter_id = $dbh->prepare("SELECT * from t_readings where meter_serial = '21001652' AND ...");
$get_meter_id->execute() or die "Couldn't execute statement: ".$get_meter_id->errstr;
my $meter_reg_id = $get_meter_id->fetchrow_array();

Above one works

where meter_serial = 21001652 AND ...")

Above one works.

where meter_serial = '".$variable."' AND ...")

Above doesn't work

where meter_serial = ".$variable." AND ...")

Above doesn't work

Many thanks.

3
  • Definately, I set $variable = 21001652; Commented Jun 28, 2010 at 5:23
  • 1
    prove it to yourself; use Data::Dumper; $Data::Dumper::Useqq=1; print Dumper($variable) Commented Jun 28, 2010 at 7:14
  • 1
    perhaps you could say what "failed" means? didn't select anything? gave an error? what error? Commented Jun 28, 2010 at 7:15

2 Answers 2

7

Use placeholders. Don't fiddle about with string concatenation.

my $get_meter_id = $dbh->prepare("SELECT * from t_readings where meter_serial=? AND ...");
my $foo = 21001652;
$get_meter_id->execute($foo) or die "Couldn't execute statement: ".$get_meter_id->errstr;
Sign up to request clarification or add additional context in comments.

Comments

5

What about:

my $get_meter_id = $dbh->prepare("SELECT * from t_readings where" .
     "meter_serial = ? AND ...");
$get_meter_id->execute($variable) or die "Couldn't execute statement: " . 
     $get_meter_id->errstr;
my $meter_reg_id = $get_meter_id->fetchrow_array();

further reading

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.