Perl脚本无法检索复选框值

时间:2014-06-25 20:12:31

标签: perl

我在同一个文件中都有以下Perl subs -

填入:

sub __populate {
    my $self = shift;

    my $sth = $self->{dbh}->prepare("select prefid, value, others_posts from user_preferences where userid=?");
    $sth->execute($self->userid);
    while(my $href = $sth->fetchrow_hashref()) {
        $self->value($href->{PREFID}, $href->{VALUE}, $href->{OTHERS_POSTS});
    }
    $sth->finish();
}

更新

sub update {
    my $self = shift;

    my $sth = $self->{dbh}->prepare("delete from user_preferences where userid=?");
    $sth->execute($self->userid);
    $sth->finish;
    $sth = $self->{dbh}->prepare("insert into user_preferences(userid, prefid, value, others_posts ) values(?, ?, ?, ?)");
    while(my ($prefid, $value, $others_posts) = each %{$self->{PREFS}}) {
        $sth->execute($self->userid, $prefid, $value, 'true');
    }
    $sth->finish;
}

和价值:

sub value {
    my $self = shift;
    my $prefid = shift;
    $self->{PREFS}->{$prefid} = shift if(@_);
    return $self->{PREFS}->{$prefid};
}

最初它只是PREFIDVALUE,但我刚刚将OTHERS_POSTS添加到populateupdate个潜点。问题是它似乎没有为我刚添加的OTHERS_POSTS返回任何内容。每次运行脚本时,OTHERS_POSTS的值都不会插入到表中。我认为问题出在我的value sub上,但我对Perl不熟悉并且不知道如何修改它以便提取OTHERS_POSTS的值。

2 个答案:

答案 0 :(得分:1)

问题是您已将每个首选项从简单的键/值对(prefid / value)更改为具有两个值(值和其他位置)的每个键。需要相应地更改您的数据结构以支持它。

因此每个prefId键需要一个包含VALUE& OTHERPOSTS条目及相关值。

对此的更改是:

sub update {
    my $self = shift;

    my $sth = $self->{dbh}->prepare("delete from user_preferences where userid=?");
    $sth->execute($self->userid);
    $sth->finish;
    $sth = $self->{dbh}->prepare("insert into user_preferences(userid, prefid, value, others_posts ) values(?, ?, ?, ?)");
    while(my ($prefid, $pref) = each %{$self->{PREFS}}) {
        $sth->execute($self->userid, $prefid, $pref->{VALUE}, $pref->{OTHERSPOSTS});
    }
    $sth->finish;
}

sub value {
    my ($self,$prefid,$value,$othersposts) = @_;
    $self->{PREFS}->{$prefid} = { VALUE => $value , 
                                  OTHERSPOSTS => $othersposts };
    return $self->{PREFS}->{$prefid};
}

__ populate()不需要更改,因为您已经将额外参数传递给value()

一直无法实际运行,因此可能会出现一些syntex错误,但希望你能得到这个想法。

答案 1 :(得分:0)

$self->{PREFS}是一个最初有prefid => value对的哈希。

如果您想在该哈希修改中存储valueother_posts

sub value {
    my ($self,$prefid,$value,$otherposts) = @_;

    # set
    if( ! defined($value)) {
        $self->{PREFS}->{$prefid} = "$value|$otherposts";
    }

    return $self->{PREFS}->{$prefid};
}

更新的新版本:

sub update {
    my $self = shift;

    my $sth = $self->{dbh}->prepare("delete from user_preferences where userid=?");
    $sth->execute($self->userid);
    $sth->finish;
    $sth = $self->{dbh}->prepare("insert into user_preferences(userid, prefid, value, others_posts ) values(?, ?, ?, ?)");
    for my $prefid (keys %{$self->{PREFS}}) {
        my ($value,$others_posts) = split '\|', $self->{PREFS}->{$prefid};
        $sth->execute($self->userid, $prefid, $value, $others_posts);
    }
    $sth->finish;
}