0

我创建了一个连接到数据库的代码,我想使用相同的按钮从数据库中删除数据以进行更新。但我只能在表格中显示数据并且不能删除。

  my $q= new CGI;
    print $q->header;
    print $q-> start_html(
       -title   => "",
    );

    # print $q->start_form;
    ## mysql user database name
    my $db = "people";
    ## mysql database user name
    my $user = "root"; 
    ## mysql database password
    my $pass = "";

    ## user hostname : This should be "localhost" but it can be diffrent too
    my $host="127.0.0.1";

    ## SQL query
    my $query = "select ID,Name,Surname,Gender from person";

    my $dbh = DBI->connect("DBI:mysql:$db:$host", $user, $pass);
    my $sqlQuery  = $dbh->prepare($query)
    or die "Can't prepare $sqlQuery: $dbh->errstr\n";
    my $rv = $sqlQuery->execute
    or die "can't execute the query: $sqlQuery->errstr";

    print start_form (-method => 'post', -action => "modify.pl" );

    my @aRows;

    while (my @data = $sqlQuery->fetchrow_array()) {      
       my $cRowId = hidden('ID', $data[0]);

       my $bt1 = submit('action','delete');
       my $bt2 = submit('action','update');

       push @aRows, ($cRowId, $q->Tr($q->td([$data[1], $data[2], $data[3],$bt1,$bt2])));
    }

    print $q->table({-border =>'1', -align =>'center',  -width => '100%'},
       $q->Tr([$q->th([ 'Name', 'Surname', 'Gender', 'Delete', 'Update', ])]),
       @aRows,
    );

    print $q->input({-type => 'button', -class => 'button', -onclick => "window.location.href='insert.pl';", -value => 'Shto'});

    print $q->end_form;  
    print $q->end_html;

删除.pl

use CGI;
use CGI qw(standard);
use DBI;
use CGI::Carp qw(set_die_handler);
use CGI qw/:all/;
    BEGIN {
       sub handle_errors {
          my $msg = shift;
          print "content-type: text/html\n\n";
          #proceed to send an email to a system administrator,
          #write a detailed message to the browser and/or a log,
          #etc....
      }

      set_die_handler(\&handle_errors);
}

my $q = CGI->new();



my $db = "people";
my $user = "root"; 
my $pass = "";
my $host="127.0.0.1";
my $dbh = DBI->connect("DBI:mysql:$db:$host", $user, $pass);
my $action = $q->param('action'){
given ($action){
           when('delete'){
               my $row_id = $q->param('ID');
               my $sth = $dbh->prepare("DELETE FROM person WHERE ID = $row_id ") or die "Can't prepare $query: $dbh->errstr\n";
               my $rv = $sth->execute() or die $DBI::errstr;               
               print "deleted";
my $sth->finish();           
my $dbh->commit or die $DBI::errstr;
          }
    } }

我不知道问题可能出在哪里

4

3 回答 3

3

绝大多数 Perl CGI 问题可以通过以下方式解决:

  • 添加use strictuse warnings到您的代码
  • 修复现在出现在错误日志中的所有错误
于 2013-07-25T12:57:03.813 回答
2

在您尝试使用该变量创建查询$row_id ,您分配一个值。

此外,在 SQL 查询中使用原始用户输入会使您容易受到XSS 攻击。重写代码以使用参数化查询

于 2013-07-25T08:41:36.233 回答
0

my如果您不想要新变量,请不要使用。my从方法调用中删除所有的:

my $sth->finish();           
my $dbh->commit or die $DBI::errstr;
于 2013-07-25T14:15:16.427 回答