我正在尝试使用一些输入到用户中的新值来更新我的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工作台中运行sql命令时,它将成功更新该行。我怎么了?
答案 0 :(得分:3)
您的SQL语句的语法有误:
UPDATE tblclasses(classname, department, classnum, grade, credits)
VALUES (?, ?, ?, ?, ?)
WHERE classID = $id
应该写成:
UPDATE tblclasses
SET classname = ?,
department = ?,
classnum = ?,
grade = ?,
credits = ?
WHERE classID = ?
请参见the mysql docs。
旁注(也由@Grinnz评论):
您应始终«严格使用»
,应在数据库或语句句柄上将DBI属性«RaiseError»设置为1;因此所有DBI错误都是致命的;同时禁用«RaiseError»和«PrintErrror»会导致DBI既不会死于错误也不会报告错误,因此您必须手动检查每个DBI调用的返回码以确保其有效-请参见the DBI docs
您应该将SQL语句中的所有变量绑定为无效的SQL注入(您没有绑定$ id,我在上面的查询中将其更改了)
答案 1 :(得分:0)
在不知道DBMS的情况下,我不能百分百确定,但是看起来好像您混合了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);