php - 如何使用 PHP 在 HTML 中创建表格

标签 php html mysql

我有 5 张图片存储在一个文件夹中,它们的链接存储在数据库中。 我想将它们放在每行三列的表格中。

<body>
<center>
<table border='1'>
<?php
$host="";
$username="";
$password="";
$db_name="fruits_db";
$tbl_name="fruits_tbl";
$connection=mysqli_connect("$host","$username","$password","$db_name");
if (mysqli_connect_errno())
{
    echo "The application has failed to connect to the mysql database server: " .mysqli_connect_error();
}
$result = mysqli_query($connection, "SELECT * FROM fruits_tbl")or die("Error: " . mysqli_error($connection));
$num_rows=mysqli_num_rows($result);
$rows =  $num_rows/3;

for($i=1; $i<=$rows ; $i++)
{
    echo "<tr>";
    for($j=1; $j<=3; $j++)
    {
        while($row = mysqli_fetch_array($result))
        {
            echo
            ("<td width='180px' height='200px'>"
             ."<div class = 'fruit_image'>"
             ."<img src='"
             .$row['fruit_image']
             ."'/>"
             ."</div>"
             ."<div class = 'fruit_title'>"
             .$row['fruit_name']
             ."</div>"
             ."</td>"
            );
        }
    }
    echo "</tr>";
}

mysqli_close($connection);
?>
</table>
</center>
</body>
</html>

我创建的上述代码包含两个 FOR 循环。该脚本应计算表中的行数,然后除以 3(HTML 表中每行的列数)。 我想知道这段代码哪里出错了。

最佳答案

在第一个 for 循环内使用 while($row = mysqli_fetch_array($result)){},它将在外部循环运行第 2/3 次之前遍历所有行。

这是另一种方法-

$counter = 1;
// start 1st row
echo "<tr>";
while($row = mysqli_fetch_array($result)){
// if the 4th cell, end last row, and start new row
    if ($counter%3==1){
        echo "</tr><tr>";
    }
    echo
        "<td width='180px' height='200px'>"
        ."<div class = 'fruit_image'>"
        ."<img src='"
        .$row['fruit_image']
        ."'/>"
        ."</div>"
        ."<div class = 'fruit_title'>"
        .$row['fruit_name']
        ."</div>"
        ."</td>";
    // increase the counter
    $counter++;
}
// close the last row
echo "</tr>";

关于php - 如何使用 PHP 在 HTML 中创建表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16878839/

相关文章:

php - 在mysql中存储设置

php - 如何使用 PHP 和 MySQL 对表值进行排序?

php - Yii2 加载数据本地 INFILE

html - 最简单的 Blogger 模板。 (博客点)

html - 如何同时拥有背景渐变和背景图片?

javascript - 如何在页面上移动图像并使其实时保持位置?

php - 代码点火器 Cron - "The controller/method pair you requested was not found"

php - Laravel 的 "withVariableName"是如何工作的?

mysql - 获取所有字段、所有行的表上的索引

php - 替代 mysqli 中的 mysql_field_name