PHP循环位置

时间:2010-04-16 20:43:46

标签: php

有人可以帮我解决这个问题。我做了一个图像上传器,我希望图像能够制作另一个tr,如果它达到5个图片,那么它就不会溢出。这是我的代码:

$dbc = mysql_connect("localhost" , "root" , "") or die (mysql_error());
mysql_select_db('blog_data') or die (mysql_error());

$sql = "SELECT * FROM img_uploaded";
$result = mysql_query($sql);

while($rows=mysql_fetch_array($result))
{
  if ($rows)
  {
    echo "<tr><td><img src='user_images/".$rows['img_name'] . "' width='100' height='100'></td></tr>";
  }
  else
  {
    echo "<td><img src='user_images/".$rows['img_name'] . "' width='100' height='100'></td>";
  }
}

mysql_close();

3 个答案:

答案 0 :(得分:1)

E.g。使用modulus operator

$dbc = mysql_connect("localhost" , "root" , "") or die (mysql_error());
mysql_select_db('blog_data', $dbc) or die (mysql_error($dbc));

$sql = "SELECT * FROM img_uploaded";
$result = mysql_query($sql, $dbc) or die(mysql_error($dbc));

echo '<table><tr><th>image</th>';
for($cnt=0; false!==($row=mysql_fetch_array($result)); $cnt++) {
  if ( 0===$cnt%5 ) {
    echo '</tr><tr>';
  }
  echo '<td><img src="user_images/'.$rows['img_name'] . '" width="100" height="100"></td>';
}
echo '</tr></table>';

答案 1 :(得分:1)

它使用模数运算符,但此外它还会检查a是否已打开。

$dbc = mysql_connect("localhost" , "root" , "") or die (mysql_error());
mysql_select_db('blog_data') or die (mysql_error());

$sql = "SELECT * FROM img_uploaded";
$result = mysql_query($sql);

$numOfRows = 0;

while($rows = mysql_fetch_array($result))
{
    if (($numOfRows % 5) === 0)
    {
        if ($numOfRows != 0)
        {
            echo '</tr>';
        }

        echo '<tr>';
    }

    $numOfRows++;

    if ($rows)
    {
        echo "<td><img src='user_images/".$rows['img_name'] . "' width='100' height='100'></td>";
    }
    else
    {
        echo "<img src='user_images/".$rows['img_name'] . "' width='100' height='100'>";
    }
}

mysql_close();

答案 2 :(得分:1)

$rows = array();
while ($row = mysql_fetch_assoc($result)) {
    $rows[] = $row;
}
$cols = 5;
$chunkSize = ceil(count($areaArray) / $cols);
echo $chunkSize * $cols;
foreach (array_chunk($rows, $chunkSize) as $itemsInThisTr) : ?>
 <tr>
<?php foreach ($itemsInThisTr as $item) : ?>
   <td><?php echo $item['img_name']; ?></td>
<?php endforeach; ?>
 </tr>
<?php endforeach; ?>