使用PHP在表中获取照片

时间:2011-10-21 11:37:01

标签: php html mysql html-table fetch

我试图以这种方式获取我的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>

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

results to my current code, how can I stop the duplication

2 个答案:

答案 0 :(得分:2)

嗯......你的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
}

答案 1 :(得分:1)

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

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>';