【问题标题】:Display Single PHP Data in 2 Columns在 2 列中显示单个 PHP 数据
【发布时间】:2018-05-29 04:43:01
【问题描述】:

我想在我的 PHP 文件中将单个数据显示为 2 列作为 mysql 表结果。我已尝试使用我的代码,但相同的数据已显示为类似<tr><td>result1</td><td>result1</td> 的结果。

我已尝试使用我的代码,但结果如下:

| result 1 | result 1 |
| result 2 | result 2 |
| result 3 | result 3 |
| result 4 | result 4 |
| result 5 | result 5 |
| result 6 | result 6 |
| result ... | result ... |

但我需要结果为

| result 1 | result 2 |
| result 3 | result 4 |
| result 5 | result 6 |
| result 7 | result 8 |
| result ... | result ... |

这是我的代码:

    <?php
        include('config.php');
        $data_content = '';
        $qry = "SELECT DISTINCT bankName FROM bankData ORDER BY bankName";
        $result = mysql_query($qry);
        while($row = mysql_fetch_array($result))
            {
                 $data_content.= "<a href='bank/".$row['bank_Name'].".php'> ".$row['bankName']."</a>";
            }
        mysql_close();
        ?>
<!DOCTYPE html>
<html lang="en">
<head>
<body>
<div>   
<table border="1">
    <?php
         for($i=0; $i<=1; $i++)
            {
            echo "<tr>";
            for($j=0; $j<=1; $j++)
            {
             echo "<td>";
             echo $data_content;
             echo "</td>"; 
            }
             echo "</tr>";
            }
    ?>
</table>
</div>
</body>
</html>

请帮帮我。

【问题讨论】:

  • 你的 for 循环没有做任何事情?

标签: php mysql html-table


【解决方案1】:

把循环放在下面:

<table border="1">
<?php
$i = 0;
while($row = mysql_fetch_array($result))
    {
         // Odd row opens
         if (++$i % 2 != 0) echo "<tr>";
         echo "<td><a href='bank/".$row['bankName'].".php'> ".$row['bankName']."</a></td>";
         // Even row closes
         if ($i % 2 == 0) echo "</tr>";  
    }
    // If you have an odd number of results, add a blank column and close the last row
    if ($i % 2 != 0)  echo "<td></td></tr>";
?>
</table>

(++$i % 2 != 0) 增加 $i 并检查它是否为奇数。如果是奇数,它将以&lt;/tr&gt; 打开表行,下一次迭代将以&lt;/tr&gt; 关闭表行。

【讨论】:

  • 它可以工作,但有一些问题。第一行的第二列显示空值。
  • 感谢您的代码.. 现在它对我来说非常有用.. 为您的答案添加了投票.. :-)
猜你喜欢
  • 2013-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-15
相关资源
最近更新 更多