我想将数据插入数据库,但它显示以下错误:Can't call method "execute" on an undefined value at C:/wamp/bin/apache/apache2.2.22/cgi-bin/ova/laura/shto.pl line 47.
my $q= new CGI;
print $q->header;
print $q-> start_html(
-title => " ",
);
my $db = "peoples";
my $user = "root";
my $pass = "";
my $host ="127.0.0.1";
my $dbh = DBI->connect("DBI:mysql:$db:$host", $user, $pass);
my $name = $q->param("Name");
my $surname = $q->param("Surname");
my $$gender = $q->param("Gender");
my $dId = $q->param("pID");
my $departamentiId = $q->param("dID");
my $sql = "INSERT INTO person (Name, Surname, Gender, pID, dID)
VALUES ('$name', '$surname', '$gender','$pId','$dId')";
my $sth = $dbh->prepare($sql);
my $sth->execute() or die $DBI::errstr;
my $sth->finish();
my $dbh->commit or die $DBI::errstr;
可能是什么错误?
答案 0 :(得分:4)
从您不想声明新变量的行中删除my
。
使用use warnings
会告诉你:
"my" variable $sth masks earlier declaration in same scope at -e line 1.
另外,使用占位符构造SQL查询,它们是safer:
my $sql = 'INSERT INTO personi (Emri, Mbiemri, Seksi, Pozicioni_ID, Departamenti_ID)
VALUES (?, ?, ?, ?, ?)';
my $sth = $dbh->prepare($sql);
$sth->execute($emri, $mbiemri, $gjinia, $pozicioniId, $departamentiId) or die $DBI::errstr;
答案 1 :(得分:2)
问题是这两行:
my $sth = $dbh->prepare($sql);
my $sth->execute() or die $DBI::errstr;
他们应该阅读:
my $sth = $dbh->prepare($sql);
$sth->execute() or die $DBI::errstr;
原因是你重新声明了变量my
的第二行$sth
(从而删除了包含STH对象的旧变量$ sth);在重新声明时,新$sth
将像所有新声明的变量一样初始化为undef
。
您应该阅读以下文档以了解Perl中的变量作用域:
my
答案 2 :(得分:0)
略微捎带choroba的答案。我也更喜欢确保“param()”返回的“默认”值是合理的,la:
my $emri = $q->param("Emri") || undef;
my $mbiemri = $q->param("Mbiemri") || "August";
my $gjinia = $q->param("Gjinia") || 0;
my $pozicioniId = $q->param("pozicioniId") || "none";
my $departamentiId = $q->param("departamentiId") || 82.4;
“param()”为缺失值返回“undef”。即使参数化查询时,undef值可能与您的预期不符。