use CGI;
use strict;
use DBI();
use CGI::Carp qw(fatalsToBrowser);
print "content-type: text/html; charset=iso-8859-1\n\n";
my $q = new CGI;
my $name = $q->param('name');
my $email = $q->param('email');
print $q->header;
#connect to database.
my $dbh = DBI->connect("DBI:mysql:database=test;host=localhost","root",
"mukesh", {'RaiseError' => 1});
eval { $dbh->do("CREATE TABLE IF NOT EXISTS emp (name VARCHAR(20), email VARCHAR(50) UNIQUE NOT NULL)") };
print "creating table emp failed: $@" if $@;
print "<br>";
$dbh->do("INSERT INTO emp(name,email) values('$name','$email')");
my $sql = qq/select * from emp order by name/;
my $sth = $dbh->prepare($sql) or die "Can't prepare $sql:$dbh->errstrn";
my $rv = $sth->execute() or die "can't execute the query: $sth->errstrn";
while (my @row = $sth->fetchrow_array) {
print join(", ",@row),"<br>";
}
$sth->finish();
$dbh->disconnect();
print "<br>Total no of records : $rv";
if ($rv>=1){
print "<br>Record has been successfully updated !!!<br>";
} else {
print "<br>Error!!while inserting record<br>";
exit;
}
当我提交相同价值的电子邮件地址的html表单时,我被重定向到另一个 页面出现以下错误:
Content-Type: text/html; charset=ISO-8859-1
Software error:
DBD::mysql::db do failed: Duplicate entry 'rajesh@gmail.com' for key 'email' at C:/Apache2/cgi-bin/connectivity.cgi line 27.
1)我不希望显示此错误,而是我想显示我自己的消息,如果电子邮件地址已经存在。像“电子邮件ID已经存在,请输入新的ID”
2)解决上述问题后,我希望它显示在同一页面上 我正在提交表格。
此行似乎无法重复输入
$dbh->do("INSERT INTO emp(name,email) values('$name','$email')");
答案 0 :(得分:4)
正如其他人所说,你可以测试一下,看看电子邮件是否已经存在,但如果有人提交你的表单,并且在你的代码的另一个副本已经测试后,它会进入插入,那么会发生什么情况。通过将插入包装在eval中(因为您已经启用了RaiseError)并且之后测试错误和状态以查看错误是否是重复条目,最好简单地捕获此条件。
eval {
$dbh->do("INSERT INTO emp(name,email) values(?,?)", undef, $name, $email);
};
if ($@) {
# you might want to use state instead of err but you did not show us the state
if ($dbh->err =~ /Duplicate entry/) {
# already registered
} else {
# report what is in $@ - it is a different error
}
}
BTW,因为你已经启用了RaiseError,你不需要继续检查来自各种DBI方法的返回(你的“或死”) - 如果它们失败并且PrintError默认为1,它们将自动死亡,因为你发现它们将打印错误。
最后一点,胖逗号(=&gt;)自动将事物字符串化为左边,因此“{'RaiseError'=&gt; 1}”可以写成“{RaiseError =&gt; 1}”。
答案 1 :(得分:3)
要处理此问题,您可以检查电子邮件地址是否已存在。
my $sth = $dbh->prepare("SELECT COUNT(*) FROM emp WHERE email = ?");
$sth->execute($email);
my $rows = $sth->fetchrow_arrayref();
$sth->finish();
if ($rows->[0] == 0) {
# Insert your email address
} else {
# Show an error message
}
正如amon指出的那样,你应该总是在你的陈述中使用占位符。