首页 文章

Perl CGI没有正确运行sql

提问于
浏览
0

我正在开发一个基本的注册页面,但我似乎无法通过用户名检查来触发或实际插入数据库 . 在这个页面中,我从我的html页面中获取了我传递的信息,并首先检查用户名是否已经存在 . 如果不是我重定向 . 否则,我将值插入数据库并重定向到新页面 . 我得到的输出是这样的:

我无法在代码中找到实际问题 .

#!/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文件只包含一个表单:

我的sql表看起来像这样 . (我在mysql workbench中手动添加了第一个帐户)

1 回答

  • 0

    只是在一个答案中总结ikegami的评论......

    您的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);
    

相关问题