gpt4 book ai didi

mysql - 无法使用 Perl 插入 MySQL

转载 作者:太空宇宙 更新时间:2023-11-03 10:44:35 25 4
gpt4 key购买 nike

我是 Perl 的新手,我一直在尝试使用这个简单的程序将值插入数据库。我有两个文件,一个将表单值发送到 Perl 文件的 HTML 文件。但是我无法执行任何插入或检索;我总是得到一个空白页面作为输出。

HTML 文件:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>8th program</title>
</head>
<body>
<form action="http://localhost:81/cgi-bin/8.pl" method="post">
NAME:<input type="text" name="name"><br>
AGE:<input type="text" name="age"><br>
<input type="submit" value="submit">
</form>
</body>
</html>

Perl 文件:

#!"C:\xampp\perl\bin\perl.exe"

print "Content-Type:text/html\n\n";

use CGI ':standard';
use DBI;

print "<html><head><title>insert</title></head>";

$dbh = DBI->connect( "DBI:mysql:test", "root", " " );

$name = param( "name" );
$age = param( "age" );

$qh = $dbh->prepare( "insert into student values('$name','$age')" );
$qh->execute();

$qh = $dbh->prepare( "select * from student" );
$qh->execute();

print "<table border size=1>
<tr>
<th>Name</th>
<th>Age</th>
</tr>";

while ( ( $name, $age ) = $qh->fetchrow() ) {
print "<tr><td>$name</td>
<td>$age</td></tr>";
}

print "</table>";

$qh->finish();

$dbh->disconnect();

print "</html>";

请帮我解决这个问题。

最佳答案

没有 DBI 方法 fetchrow。在这种情况下,您的意思似乎是 fetchrow_array

另外,请注意这几点

  • 在 Windows 系统上,shebang 行将被忽略,除非在那里指定的任何命令开关都将被接受。必须在别处定义 perl 编译器/解释器的路径

  • 必须始终

    use strict;
    use warnings 'all';

    在您编写的每个 Perl 程序的顶部,并尽可能靠近其第一个使用点声明每个变量

  • 您应该使用占位符,而不是将参数插入到 SQL 字符串中。比如这样

    my $qh = $dbh->prepare( 'INSERT INTO student (name, age) VALUES (?, ?)' );
    $qh->execute($name, $age);
  • 调用finish是错误的。 The documentation有这个

    Adding calls to "finish" after [a] loop that fetches all rows is a common mistake, don't do it, it can mask genuine problems like uncaught fetch errors.

关于mysql - 无法使用 Perl 插入 MySQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33717281/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com