用perl cgi更新db行

9rnv2umw  于 2021-06-17  发布在  Mysql
关注(0)|答案(2)|浏览(329)

我正在尝试用输入到用户中的一些新值更新我的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命令时,它成功地更新了行。我的问题是什么?

uqxowvwt

uqxowvwt1#

如果不知道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);
qqrboqgw

qqrboqgw2#

sql语句的语法有错误:

UPDATE tblclasses(classname, department, classnum, grade, credits) 
VALUES (?, ?, ?, ?, ?)
WHERE classID = $id

应写:

UPDATE tblclasses
SET classname = ?, 
       department = ?,
       classnum = ?,
       grade = ?,
       credits = ?
WHERE classID = ?

查看mysql文档。
旁注(同样由@grinnz评论):
你应该一直« 使用严格的 »
应该设置dbi属性« 提升误差 » 在数据库或语句句柄上设置为1;因此,所有的dbi错误都是致命的;禁用两者« 提升误差 » 以及« 打印机错误 » 结果dbi既不会因错误而死亡,也不会报告错误,因此您必须手动检查每个dbi调用的返回代码,以确保它工作正常-请参阅dbi文档
您应该绑定sql语句中的所有变量以使sql注入无效(您没有绑定$id,我在上面的查询中更改了它)

相关问题