【问题标题】:Fetching photos in a table using PHP [closed]使用 PHP 在表格中获取照片 [关闭]
【发布时间】:2017-10-29 20:26:25
【问题描述】:

我正在尝试以这种方式获取我的 mysql 数据,每行 5 张照片,最多 2 行这似乎不起作用,因为循环不断复制我拥有的 2 行中的照片。

这是我的代码:

    <table border="1" width="%">
<?php
while($info = mysql_fetch_array( $data )) 
                    {

for ($tr=1;$tr<=3;++$tr)
            {
                echo "<tr>";
                for ($td=1;$td<=5;++$td)
                {   


                echo "<td><img width=125 height=125 src=images/".($info['photo']). "></td>";

                }

                echo "</tr>" ;
            }

 }
            ?>

</table>

请帮我解决这个问题,结果一直处于这种状态:

【问题讨论】:

标签: php html mysql html-table fetch


【解决方案1】:

嗯...您的 while 循环遍历所有照片。由于您的 for 循环,您对每张照片进行 3 * 5 次迭代。您实际上可能想要做的是这样的事情:

$column = 0;
$row = 0;
while($info = mysql_fetch_array( $data ))  {
    $column++;
    if ($column == 5) {
        echo '</tr><tr>';
        $column = 1;
        $row++;
    }
    if ($row == 2) {
        break;
    }
    // output your image here
}

【讨论】:

  • 最好为 SQL 查询添加限制以获取不超过 3*5=15 的图像,即 .. WHERE ... LIMIT 15;
【解决方案2】:

遵循一个非常简单的方法..首先将获取的图像复制到一维数组中,然后将它们相应地放入表中

while ($ans = mysql_fetch_array($data)) {
  $image[] = $ans['photo'];
}
echo '<table>';   
for ($tr = 1; $tr<=2; $tr++) { 
  echo '<tr>';
  for ($td = 1; $td <= 5; $td++) {

    $img = 'images/' . $info[$td*$tr];
    echo '<td><img src="$img" /></td>';
  }
  echo '<tr/>';
}
echo '</table>';

【讨论】:

    猜你喜欢
    • 2013-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-13
    相关资源
    最近更新 更多