我正在尝试使用输入到用户的一些新值来更新我的sql表。由于某种原因,sql命令没有更新我的数据库。我得到了我验证的正确值。这是我的代码
#!/usr/bin/perl
#This is going to be the user login check and will set a cookie
use DBI;
use CGI qw(:standard);
use strict;
#Connection error
sub showErrorMsgAndExit {
print header(), start_html(-title=>shift);
print (shift);
print end_html();
exit;
}
#Connecting to the database
my $dbUsername = "root";
my $dbPassword = "password";
my $dsn = "DBI:mysql:f18final:localhost";
my $dbh = DBI->connect($dsn, $dbUsername, $dbPassword, {PrintError => 0});
#error checking
if(!$dbh) {
print header(), start_html(-title=>"Error connecting to DB");
print ("Unable to connec to the database");
print end_html();
exit;
}
print header;
print start_html(-title=>'Add Classes');
#Get the information the user entered
my $id = param('classid');
my $className = param('classname');
my $department = param('department');
my $classnum = param('classnum');
my $grade = param('grade');
my $credits = param('credit');
print "$id $className, $department, $classnum, $grade, $credits";
#first sql check to see if username is already taken
my $check = "UPDATE tblclasses(classname, department, classnum, grade, credits) VALUES (?, ?, ?, ?, ?) WHERE classID = $id";
my $sth = $dbh->prepare($check);
$sth->execute($className, $department, $classnum, $grade,$credits);
print "<h1>Success</h1>";
print "<form action=http://localhost/cgi-bin/edit.pl method = 'post'>";
print "<input type = 'submit' name = 'submit' value = 'Update Another'>";
print "</form>";
print "<form action=http://localhost/cgi-bin/actions.pl method = 'post'>";
print "<input type = 'submit' name = 'submit' value = 'Back to actions'>";
print "</form>";
print end_html();
exit;
当我尝试在mysql workbench中运行sql命令时,它成功更新了该行。我的问题是什么?
SQL语句的语法有错误:
UPDATE tblclasses(classname, department, classnum, grade, credits)
VALUES (?, ?, ?, ?, ?)
WHERE classID = $id
应写成:
UPDATE tblclasses
SET classname = ?,
department = ?,
classnum = ?,
grade = ?,
credits = ?
WHERE classID = ?
附注(由@Grinnz评论):
在不知道DBMS的情况下,我不能100%确定,但看起来好像你混合了insert和update命令的语法。更新的正确语法应该是:
UPDATE tblclasses
set
classname = ?,
department = ?,
classum = ?,
grade = ?,
credits = ?
WHERE classID = $id
此外,对于它的价值,您还应该能够将$id
变量作为参数传递,而不是对其进行插值。从理论上讲,这将对数据库更友好,因为它将编译一次并反复执行相同的SQL语句,只有不同的绑定变量值:
my $check = qq{
UPDATE tblclasses
set
classname = ?,
department = ?,
classum = ?,
grade = ?,
credits = ?
WHERE classID = ?
};
my $sth = $dbh->prepare($check);
$sth->execute($className, $department, $classnum, $grade,$credits, $id);