使用 MySQL 的 CGI:如何显示来自 table 的所有数据?
CGI using MySQL: How to display all data from table?
这是作业。当我 运行 脚本时,它只会显示数据库中的一行数据。我认为 my @record = $sql->fetchAll();
是问题所在。我该怎么做才能输出 table?
中的所有行
use CGI qw(:standard);
use CGI::Carp qw(fatalsToBrowser);
use DBI;
use strict;
use warnings;
my $idnum = param('idnum');
my $year = param('year');
my $make = param('make');
my $model = param('model');
my $color = param('color');
my $price = param('price');
print "Content-type: text/html \n\n";;
my $db = "DBI:mysql:cars:localhost";
my $dbh = DBI->connect($db,"root","",{RaiseError=>1});
my $sql = $dbh->prepare(qq(select * from cars));
$sql->execute;
print <<here;
<div align="center">
<h2>Cars</h2>
<table border ="2" bordercolor="green">
<tr>
<td>Id</td><td>Year</td><td>Make</td><td>Model</td><td>Color</td> <td>Price</td>
</TR>
here
my @record = $sql->fetchrow_array; ### there is only one row in resultset
for(my $i = 0; $i < @record; $i++ ) {
print "<td>$record[$i]</td>";
}
print "</tr>";
print "</table></div></body></html>";
$dbh->disconnect();
fetchrow_array
方法一次只 returns 一行,直到用完为止。这是一个迭代器。所以你的代码一次正确地打印一行。
您需要迭代结果,直到没有更多结果为止。
while (my @record = $sql->fetchrow_array) {
print "<tr>";
print "<td>$_</td>" foreach @record;
print "</tr>";
}
我使用了相当短的 foreach @record
,它为您提供了数组中的每个元素,一个接一个。这样你就不需要处理索引。把它放在你想在循环中重复的行之后称为 postfix notation.
这是作业。当我 运行 脚本时,它只会显示数据库中的一行数据。我认为 my @record = $sql->fetchAll();
是问题所在。我该怎么做才能输出 table?
use CGI qw(:standard);
use CGI::Carp qw(fatalsToBrowser);
use DBI;
use strict;
use warnings;
my $idnum = param('idnum');
my $year = param('year');
my $make = param('make');
my $model = param('model');
my $color = param('color');
my $price = param('price');
print "Content-type: text/html \n\n";;
my $db = "DBI:mysql:cars:localhost";
my $dbh = DBI->connect($db,"root","",{RaiseError=>1});
my $sql = $dbh->prepare(qq(select * from cars));
$sql->execute;
print <<here;
<div align="center">
<h2>Cars</h2>
<table border ="2" bordercolor="green">
<tr>
<td>Id</td><td>Year</td><td>Make</td><td>Model</td><td>Color</td> <td>Price</td>
</TR>
here
my @record = $sql->fetchrow_array; ### there is only one row in resultset
for(my $i = 0; $i < @record; $i++ ) {
print "<td>$record[$i]</td>";
}
print "</tr>";
print "</table></div></body></html>";
$dbh->disconnect();
fetchrow_array
方法一次只 returns 一行,直到用完为止。这是一个迭代器。所以你的代码一次正确地打印一行。
您需要迭代结果,直到没有更多结果为止。
while (my @record = $sql->fetchrow_array) {
print "<tr>";
print "<td>$_</td>" foreach @record;
print "</tr>";
}
我使用了相当短的 foreach @record
,它为您提供了数组中的每个元素,一个接一个。这样你就不需要处理索引。把它放在你想在循环中重复的行之后称为 postfix notation.