【发布时间】:2017-04-18 09:54:35
【问题描述】:
我正在编写一个 Perl 程序,将姓名和年龄信息插入 MySQL 表并显示该表的当前内容。
这是 XHTML 数据
<?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>Perl Database Interfaces</title>
</head>
<body>
<form action="/cgi-bin/10.pl" method="post">
<p> <b>Enter Your Information</b> <br />
Name: <input type="text" name="name" /> <br />
Age: <input type="text" name="age" /> <br />
<input type="submit" value="Add" />
<input type="reset" value="Clear" />
</p>
</form>
</body>
</html>
这里是 Perl 代码
#!/usr/bin/perl
use CGI ':standard';
print "content-type:text/html\n\n";
use DBI;
$dbh = DBI->connect( "DBI:mysql:Temp", "root", "" );
$name = param( "name" );
$age = param( "age" );
$sql = "insert into Students values ('$name','$age')";
$sth = $dbh->prepare( "$sql" );
$sth->execute;
$sql = "select * from Students";
$sth = $dbh->prepare( $sql );
$sth->execute;
print "<table border size=1> <tr>
<th>Name</th>
<th>Age</th> </tr> ";
while ( ( $name, $age ) = $sth->fetchrow() ) {
print "<tr>
<td>$name</td>
<td>$age</td>
</tr> ";
}
$sth->finish();
$dbh->disconnect();
print "</table>";
数据正在插入数据库(我使用终端手动检查),但数据未显示在 Web 浏览器上。显示表格标题,但不显示行。查看我得到的输出
我做错了什么?
【问题讨论】:
-
这段代码有很多问题,但您要问的具体问题是语句句柄没有名为
fetchrow的方法。 -
过去 10 年编写的任何 Perl 代码都需要在顶部有
use strict和use warnings。 -
好的。你能告诉我可以用什么代替 fetchrow() 吗?
-
fetchrow_array?fetchrow_arrayref?fetchrow_hashref?fetchall_arrayref?它们都在 DBI 文档中,如果您费心阅读它就会知道!