-1

我想将数据插入数据库,但它显示以下错误: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;

可能是什么错误?

4

3 回答 3

4

my从您不想声明新变量的行中删除。

使用use warnings会告诉你:

"my" variable $sth masks earlier declaration in same scope at -e line 1.

此外,使用占位符来构造 SQL 查询,它们更安全

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;
于 2013-07-25T13:39:10.160 回答
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 中的变量作用域:

于 2013-07-25T13:40:12.643 回答
0

稍微捎带了choroba的答案。我也更喜欢确保从“param()”返回的“默认”值是合理的,例如:

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 值也可能不是您所期望的。

于 2013-07-25T15:24:58.573 回答