【问题标题】:PHP tables consisting of 3 rows loaded from SQL database由 SQL 数据库加载的 3 行组成的 PHP 表
【发布时间】:2023-11-29 14:00:01
【问题描述】:

我有一个加载了不同教堂信息的数据库,我正在尝试将数据库中的所有信息插入到一个包含 3 行的 PHP 表中。

我希望每个单元格的结构是:

Church Name
Image
Pastor Name

我可以轻松地将所有数据插入到一个表中,但我无法让它显示为 3 行。

echo("<table>");
while($row = mysql_fetch_array($rs))
{
        echo("<tr>");
        echo("<td>");
        echo("<a href='" . $row['website'] . "'>" . $row['churchName'] . "</a><br>");
        echo("<img src=\"" . $row['image'] . "\"><br>");
        echo($row['pastorName'] . "<br><br>");
        echo("</td>");
        echo("<td>");
        echo("<a href='" . $row['website'] . "'>" . $row['churchName'] . "</a><br>");
        echo("<img src=\"" . $row['image'] . "\"><br>");
        echo($row['pastorName'] . "<br><br>");
        echo("</td>");echo("<td>");
        echo("<a href='" . $row['website'] . "'>" . $row['churchName'] . "</a><br>");
        echo("<img src=\"" . $row['image'] . "\"><br>");
        echo($row['pastorName'] . "<br><br>");
        echo("</td>");
        echo("</tr>");

}
echo("</table>");

这样做会导致我的 3 行结构正确,但数据重复。我知道我没有更改 id,但不知道我应该怎么做

【问题讨论】:

标签: php sql html-table rows


【解决方案1】:

您正在重复行上的数据。如果要每行显示3个项目,则需要添加一个计数器和一个语句来绘制表格的换行符,如下所示:

$int_Col = 1;
echo("<table>");
while($row = mysql_fetch_array($rs))
{
    if ($int_Col == 1) {
       echo("<tr>");
    }

    echo("<td>");
    echo("<a href='" . $row['website'] . "'>" . $row['churchName'] . "</a><br>");
    echo("<img src=\"" . $row['image'] . "\"><br>");
    echo($row['pastorName'] . "<br><br>");
    echo("</td>");

    if ($int_Col == 3) { 
        echo("</tr>");
        $int_Col = 1;
    } else {
      $int_Col++;
    }
}

if ($int_Col > 1) { 
   echo("<td colspan='". (3 - $int_Col) ."'>&nbsp;</td></tr>");
}
echo("</table>");

最后一次检查 ($int_Col > 1) 应确保使用空单元格正确呈现表格 - 应跨越当前行上未绘制的正确数量的单元格。

【讨论】:

  • 非常感谢,该解决方案效果很好,我之前尝试过非常相似的方法,但忽略了添加最后一个 $int_Col
【解决方案2】:

澄清一下,我认为这里的“行”有两种定义。

  • MySQL 表行
  • HTML 表格行

我相信您是在将 3 个 MySQL 表行合并到一个 HTML 表行中。

使用以下命令将 HTML 行每 3 行拆分一次:

$i = 0;
while($row = mysql_fetch_array($rs))
{
    // whatever you're already doing(ish)

    $i++;
    if($i % 3 == 0)
    {
         echo('</tr><tr>');
    }
}

如果 MySQL 行的总数不能完全除以 3,则需要进行一些额外检查,因为在这种情况下,您将在末尾有一个或两个空单元格要填充表。

【讨论】:

    【解决方案3】:

    如果我的代码正确,您将为数据库中的每一行创建 3 行。 mysq_fetch 将为每一行运行循环,因此循环的正确内容是:

        echo("<tr>");
        echo("<td>");
        echo("<a href='" . $row['website'] . "'>" . $row['churchName'] . "</a><br>");
        echo("<img src=\"" . $row['image'] . "\"><br>");
        echo($row['pastorName'] . "<br><br>");
        echo("</td>");
        echo("</tr>");
    

    【讨论】:

      最近更新 更多