如何显示PHP抓取的数据在一个表格行中,只需要显示一个字段的数据

问题描述 投票:0回答:2

我对 PHP 还很陌生,只是花了几个小时观看视频并编写了第一个 PHP 代码。我在显示 PHP 获取数据到前端 html 表时遇到一个问题。

下面是我的数据库、代码和前端页面。

This is my database field and data This is my PHP code

<?php
 $conn=mysqli_connect("localhost","root","123456","links");
 $sql="SELECT * FROM `countries` WHERE `continent`='Asia'";
 $result =$conn->query($sql);
 echo '<h2 align="center">List of Countries in Asia</h2>';
 echo '<table align="center" width="800px" border="1" cellspacing="0" cellpadding="1"><tr align="center"><td colspan="4">Asia</td><tr>';
 echo '<tr><th>id</th><th>code</th><th>Country Name</th><th>Continent</th></tr>';
 while($row = mysqli_fetch_array($result))
 {
 
     echo 
            "<tr align='center'><td>{$row['id']}</td> ".
          "<td>{$row['code']} </td> ".
          "<td>{$row['name']} </td> ".
          "<td>{$row['continent']} </td> ".
          "</tr>";
 }
  echo '</table>';

This is browser shows

现在我只想在表中显示国家/地区字段,不需要其他字段,我不知道如何实现,我做了一个html页面,这就是我想要显示的内容。

This is what I want to achieve

有谁可以帮助我并指出实现它的路线图和逻辑,预先感谢。

我尝试了几个小时但仍然无法得到这个,我只想显示一个字段数据库数据并显示在一行然后另一行。

php html mysql fetch
2个回答
0
投票

您只想显示国家/地区名称。在这种情况下,您可以删除其他字段。唯一真正的问题是何时开始新行。

您可以通过计算在表中放入了多少个国家/地区名称来解决此问题,并使用

$counter
。将
$counter
初始化为零,因为您在开始时尚未添加任何国家/地区。然后,每次回显国家/地区名称时,
$counter
的值就会增加一。

然后是真正棘手的一点:每次显示五个国家/地区时,您都需要开始一个新行。我使用 模运算符

$counter % 5
来完成此操作。当
$counter
是五的整数倍时,
$counter
除以五的余数为零。

这会产生下面的代码。

echo '<h2 align="center">List of Countries in Asia</h2>';
echo '<table align="center" width="800px" border="1" cellspacing="0" cellpadding="1">';
echo "<tr>";
$counter = 0;
while($row = mysqli_fetch_array($result))
{
    echo "<td align='left'>{$row['name']} </td>";
    $counter++;
    if ($counter % 5 == 0) {
        echo '</tr><tr>';
    }
}
echo '</tr>';
echo '</table>';

我无法测试这段代码,因为我没有你的数据库,但我认为它应该可以工作。

此解决方案仍然适用于表格,就像您的代码中一样。更现代的方法是使用网格布局,如评论中shingo所建议。


0
投票
while ($row = mysqli_fetch_array($result)) {
    echo "<tr align='center'><td>{$row['name']}</td></tr>";
}

echo '</table>';
?>
© www.soinside.com 2019 - 2024. All rights reserved.