我正在基本注册页面上工作,但似乎无法获取用户名检查来触发或实际插入数据库。在此页面中,我将获取从html页面传入的信息,然后首先检查用户名是否已存在。如果没有,我重定向。否则,我将这些值插入db并重定向到新页面。我得到的输出是这样的:
我无法找到代码中的实际问题。
#!/usr/bin/perl
#This is going to be the user login check and will set a cookie
use DBI;
use CGI qw(:standard);
print "Content-type: text/html\n\n"; #Tells website to print content
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=>'Registration Page');
#Get the information the user entered
my $username = param('username');
my $password = param('password');
my $name = param('name');
#first sql check to see if username is already taken
my $check = "SELECT * from tblusers WHERE login = $username";
my $sth = $dbh->prepare($check);
$sth->execute();
if($sth->fetchrow_array) {
print "<p>The user already exists. You will be redirected to register page in 5 seconds.</p>";
print qq{<meta http-equiv="refresh" content = "5; url=/var/www/html/register.html"};
} else {
#prepare to enter the content into the db
my $sql = "INSERT INTO tblusers(login, password, name) VALUES($username, $password, $name)";
my $sth = $dbh->prepare($sql);
$sth->execute();
print "<p>Successfuly registered. You will be redirected to login in 5 seconds.</p>";
print qq{<meta http-equiv="refresh" content = "5; url=/var/www/html/login.html"};
}
print end_html();
exit;
编辑:该帖子的更多详细信息
我在register.cgi上运行chmod,并在perl register.cgi上运行,这就是输出。
html文件仅包含以下形式:
答案 0 :(得分:0)
只需在一个答案中总结池上的评论...
您的SQL查询中有错误。字符串变量在查询中传递时需要加引号。这将在数据库中生成一个错误,但是您将看不到它,因为您没有在句柄上设置RaiseError属性,并在其上禁用了PrintError。
在连接数据库时启用错误管理:
my $dbh = DBI->connect($dsn, $dbUsername, $dbPassword, {RaiseError => 1});
为避免引用问题,同时保护您的代码免遭SQL注入,请使用绑定参数。
查找用户时:
my $check = "SELECT * from tblusers WHERE login = ?";
my $sth = $dbh->prepare($check);
$sth->execute($username);
创建新用户时:
my $sql = "INSERT INTO tblusers(login, password, name) VALUES(?, ?, ?)";
my $sth = $dbh->prepare($sql);
$sth->execute($username, $password, $name);