我想使用perl CGI从数据库中删除数据,但它显示错误: 全局符号“$ queryDelete”需要在Dbm.pm第10行显式包名。
package Dbm;
use DBI;
use strict;
use POSIX "fmod";
sub connection {
return DBI->connect("DBI:mysql:boys:127.0.0.1" ,'root','');
};
sub do_delete {
my $rData = shift;
$queryDelete = " WHERE ";
my $cWhere = get_condition($rData);
my $queryDelete="DELETE FROM $rData->{table} $cWhere";
my $dbh = connection;
my $sqlDelete = $dbh->prepare($queryDelete) or die "Can't prepare $queryDelete: $dbh->errstr\n";
return ($sqlDelete->execute) or die "can't execute the query: $sqlDelete->errstr";
}
sub get_condition{
my $rData = shift;
my $cWhere = " 1=1 ";
while (my ($key,$value) = each $rData->{condition}) {
if (ref($value) eq 'ARRAY'){
$cWhere .= " AND ";
#print $key.$value->[0];
my $counter=0;
foreach my $cValueArray (@{$value}){
if(fmod($counter,3)==0) {
$cWhere.=" ".$key." ".$cValueArray." ";
}
else {
$cWhere.= " ".$cValueArray. " ";
}
$counter++;
}
}else{
#print "$key=$value\n
$cWhere .= " AND ". $key."=". $value;
}
};
return $cWhere;
}
1;
test.pl
my $q = new CGI();
my $handle = Dbm::connection();
sub test_delete{
my $rData = {
table =>'boys',
condition => {
ID => 99,
Emri => ['<>','\'mon\'','AND','like','\'boy%\''],
}
};
return Dbm::do_delete($rData);
};
print $q-> start_html(
-title => "Main",
-style => [ {-src =>'/media/css/ui-lightness/jquery-ui-1.10.3.custom.css', -rel=>'alternate'},
{-src =>'/media/css/ui-lightness/mystyle.css', -rel=>'stylesheet', -type=>'text/css'}
],
-script => [
{ -src=>'/media/js/jquery-1.9.1.js'},
{ -src=>'/media/js/jquery-ui-1.10.3.custom.js' }
]
);
print test_delete();
答案 0 :(得分:3)
您正在使用strict
。非常好。
sub do_delete {
my $rData = shift;
$queryDelete = " WHERE ";
my $cWhere = get_condition($rData);
my $queryDelete="DELETE FROM $rData->{table} $cWhere";
...
在这里,您尝试使用变量$queryDelete
(在其中为其分配“WHERE”)之前用my
声明它,之后两行。那很糟。您必须在使用变量之前声明它们。
您可以将my
移至第一次使用$queryDelete
,但可能不会非常有用,因为您刚刚覆盖它时稍后为它分配一个新字符串。
我的猜测是你可能会尝试这样做:
sub do_delete {
my $rData = shift;
my $cWhere = get_condition($rData);
my $queryDelete="DELETE FROM $rData->{table} WHERE $cWhere";
...
答案 1 :(得分:2)
您没有在正确的位置定义$ query Delete变量。您首先使用它并在之后定义它。尝试:
my $queryDelete = " WHERE ";
...
$queryDelete="DELETE FROM $rData->{table} $cWhere";
而不是
$queryDelete = " WHERE ";
...
my $queryDelete="DELETE FROM $rData->{table} $cWhere";