Mysql date_add 1年

时间:2013-11-21 03:16:45

标签: mysql perl

有人可以帮我弄清楚为什么加1年对我不起作用?

我有6个其他条件(1天,1周,2个月等)。唯一一个不工作的是今年。

任何人都明白为什么?如果重要,那就是Perl。

elsif ($data{length} == "6month")
{
$store = qq(INSERT INTO main (creator_name,email2,relationship,reason,email1,name1,creator_email,email3,name2,name3,creator_url,victim_url,length_of_stay,release_date) VALUES("$data{creatorname}","$data{email2}","$data{relationship}","$data{reason}","$data{email1}","$data{person1}","$data{creatoremail}","$data{email3}","$data{person2}","$data{person3}", "$creatorURL", "$victimURL","$data{length}", DATE_ADD(NOW(), INTERVAL 6 MONTH)) );
}
elsif($data{length} == "1year")
{
$store = qq(INSERT INTO main (creator_name,email2,relationship,reason,email1,name1,creator_email,email3,name2,name3,creator_url,victim_url,length_of_stay,release_date) VALUES("$data{creatorname}","$data{email2}","$data{relationship}","$data{reason}","$data{email1}","$data{person1}","$data{creatoremail}","$data{email3}","$data{person2}","$data{person3}", "$creatorURL", "$victimURL","$data{length}", DATE_ADD(NOW(), INTERVAL 1 YEAR)) );
}

my $sth = $dbh->prepare($store);
$sth->execute() or die $dbh->errstr;

2 个答案:

答案 0 :(得分:3)

你应该使用'eq'运算符来比较perl中的字符串。

elsif ( $data{length} eq '6month') {

如果你在sql语句中使用占位符也会更好。这是因为:

  • 它们几乎相同
  • 它将保护您免受sql注入
  • 你可以多次使用一个预备语句,但是时间更快 你在循环中的类似陈述
  • 您将减少重复的代码。不要重复自己

您的代码如下:

my $interval = 0;
...
elsif ( $data{length} eq '6month' ) {
    $interval = 6;
}
elsif( $data{length} eq '1year' ) {
    $interval = 12;
}
my $sth = $dbh->prepare( 'INSERT INTO main ( creator_name, email2, relationship, reason, email1, name1, creator_email, email3, name2, name3, creator_url, victim_url, length_of_stay, release_date ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, DATE_ADD(NOW(), INTERVAL ? MONTH) );' );
$sth->execute( $data{creatorname},
               $data{email2},
               $data{relationship},
               $data{reason},
               $data{email1},
               $data{person1},
               $data{creatoremail},
               $data{email3},
               $data{person2},
               $data{person3},
               $creatorURL,
               $victimURL,
               $data{length},
               $interval
             ) or die $dbh->errstr;

如果必须这样做,请在循环中插入循环移动$dbh->prepare语句。

答案 1 :(得分:2)

根本问题是你没有启用警告;如果你有,你会得到这样的警告:

$ perl
use warnings;
$data{length} = "1year";

if ($data{length} == "1month") {
    print "yes, 1month does == 1year\n";
}
__END__
Argument "1month" isn't numeric in numeric eq (==) at - line 4.
Argument "1year" isn't numeric in numeric eq (==) at - line 4.
yes, 1month does == 1year