【问题标题】:How do I handle a varying number of items from a database query?如何处理来自数据库查询的不同数量的项目?
【发布时间】:2011-09-27 21:55:34
【问题描述】:

实际上是:How can I display data in table with Perl的副本

那里接受的答案适用于此。一些替代品也是如此。


我正在尝试从 Perl 程序运行原始数据库查询并向用户显示结果。像select * from table 这样的东西。我想在 HTML 表格中显示信息。 HTML 表中的列与返回的列相对应。

我遇到了一些问题。我可以运行describe table 查询来返回表中的列数。但是,我将如何将返回结果中的信息存储到数组中?

所以如果我这样存储结果:

while (($f1, $t2, $n3, $k4, $d5, $e6) = $sth1->fetchrow_array)

在这种情况下,我只知道有四列(我从描述表中得到)。但是这个数字 4 是动态的,可以根据表名而改变。我不能根据这个数字声明我的变量。有什么建议吗?

【问题讨论】:

    标签: perl dbi


    【解决方案1】:

    试试:

    print "<table>\n";
    
    # display HTML header
    @cols = @{$sth->{NAMES_uc}};
    print "<tr>".join("", map { "<th>${_}</th>" } @cols)."</tr>\n";
    
    # display one HTML table row for each DB row
    while (my @row = $sth->fetchrow_array) {
      print "<tr>".join("", map { "<td>${_}</td>" } @row)."</tr>\n";
    }
    print "</table>\n";
    

    【讨论】:

      【解决方案2】:
      while (my @row = $sth->fetchrow_array)
      {
              print "<tr>".join("", map{ "<td>${_}</td>" } @row)."</tr>"  ;
      }
      

      【讨论】:

      • 不需要加入。 print 需要一个列表。所以你可以说: print '', map("$_"), @row), ';
      【解决方案3】:

      使用另一个问题的答案中建议的技术 - 使用 fetchrow_array 获取数组:

      while (my @row = $sth->fetchrow_array())
      {
          ...process array...
      }
      

      或使用fetchrow_array() 的替代品,例如fetchrow_hashref()

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-04-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多