无法显示数据库中的数据

时间:2016-12-03 16:32:52

标签: mysql perl xhtml

我正在编写一个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浏览器上。显示表标题但不显示行。看看我得到的输出

1

我做错了什么?

1 个答案:

答案 0 :(得分:0)

代码

use strict;
use warnings;

use CGI qw(:standard);
use DBI;

my $dbh = DBI->connect("dbi:SQLite:dbname=:memory:", undef, undef, {
    RaiseError => 1,
    PrintError => 0,
});

$dbh->do(q{
    create table students (
        name varchar(255),
        age int
    )
});

my $name = param("name");
my $age  = param("age");
$dbh->do(q{insert into students values (?, ?)}, undef, $name, $age);

print header();
print <<'EOF';
<table border='1'>
  <tr>
    <th>Name</th>
    <th>Age</th>
  </tr>
EOF

my $sth = $dbh->prepare(q{select name, age from students});
$sth->execute;

while (($name, $age) = $sth->fetchrow_array) {
    print <<EOF;
  <tr>
    <td>$name</td>
    <td>$age</td>
  </tr>
EOF
}

print qq~</table>\n~;

命令行

$ perl 40949974.pl 'name=John Smith&age=30'

输出

Content-Type: text/html; charset=ISO-8859-1

<table border='1'>
  <tr>
    <th>Name</th>
    <th>Age</th>
  </tr>
  <tr>
    <td>John Smith</td>
    <td>30</td>
  </tr>
</table>

解释

通过使用内存中的SQLite数据库并通过命令行提供CGI参数,我们有一个完整的,自包含的示例。对于插入,除非您插入一堆记录(例如,在循环中),否则您实际上不需要prepare / execute循环。我还使用了占位符并为插入绑定了值,这可以为您正确地转义变量。但是,如果您通过网页接受用户输入,则还需要进行其他验证。

您可以阅读DBI documentation以了解有关这些概念的更多信息。

相关问题