SQL插入/更新失败,不会调用错误

时间:2014-04-08 17:12:40

标签: mysql perl dbi

下午大家,

我目前正尝试在一些简单的验证后通过params将表单字段值插入或更新到mysql中。表单提交,但实际上并不执行任何操作,也不会引发语法或数据库连接错误。我知道我的连接字符串是有效的,因为我从中获取了值,以便在下面显示的嵌套评估块之前的代码中进行比较。插入foreach循环作为验证表中确实已更改值的替代方法。非常感谢您的帮助:

my $dbusr = param("dbuser");
    my $dbpw = param("dbpass");
    my $dbmail = param("dbemail");
    my $dbtel = param("dbphone");
    my $postflag = param("Submit");

    if ($dbusr ne "") {
        $sth = $dbh->prepare("SELECT * FROM USER WHERE username LIKE ?");
        $sth->execute('$dbusr');
        warn( $DBI::errstr ) if ( $DBI::err );

        my @results = $sth->fetchall_arrayref();

        foreach(@results){
            if ($dbusr eq $_){
                $loopval = 1;
            }
        }

        unless($loopval){
            $sth = $dbh->prepare("INSERT INTO USER
                       (username, password, phone, email)
                        values
                       (?,?,?,?)");
            $sth->execute($dbusr, $dbpw, $dbtel, $dbmail);
            warn( $DBI::errstr ) if ( $DBI::err );

            $sth = $dbh->prepare("SELECT * FROM USER WHERE username LIKE ?");
            $sth->execute('$dbusr');

            @results = $sth->fetchall_arrayref();

            foreach(@results){
                if ($dbusr eq $_){
                    $successflag = 1;
                }
            }
        }
        else{
            $sth = $dbh->prepare("UPDATE USER
                        SET (password = ?, phone = ?, email = ?)
                        WHERE username = ?");
            $sth->execute($dbpw, $dbtel, $dbmail, $dbusr);
            warn( $DBI::errstr ) if ( $DBI::err );

            $sth = $dbh->prepare("SELECT * FROM USER WHERE username LIKE ?");
            $sth->execute('$dbusr');

            @results = $sth->fetchall_arrayref();

            foreach(@results){
                if ($dbusr eq $_){
                    $successflag = 1;
                }
            }
        }
    }

2 个答案:

答案 0 :(得分:2)

Basic Perl:' - 引用的字符串不插入变量:

    $sth->execute('$dbusr');
                  ^--    ^---

您确实将$db等传递给您的查询作为占位符值。

尝试

     $sth->execute($dbusr); // note the lack of ' quotes

代替。

答案 1 :(得分:0)

您正在使用rows语句搜索整个SELECT * FROM USER WHERE username LIKE ?,然后使用

一次性获取所有行
my @results = $sth->fetchall_arrayref();

该方法"returns a reference to an array that contains one reference per row.",但您将返回的值视为用户名列表:

foreach(@results){
    if ($dbusr eq $_){
        $loopval = 1;
    }
}

要完成这项工作,您应该只获取username列,并将返回的行视为引用的引用。当您在数据库中查找完全匹配时,将LIKE替换为=

$sth = $dbh->prepare("SELECT username FROM USER WHERE username = ?");
$sth->execute($dbusr); # no quoting
die( $DBI::errstr ) if ( $DBI::err ); # what else to do if the execute fails?

my $results = $sth->fetchall_arrayref();  # an arrayref is returned

foreach(@$results){  # de-reference the array
    if ($dbusr eq $_->[0]){  # each row is an arrayref, look in first element
        $loopval = 1;
    }
}

(当然这同样适用于第二次搜索。)