PHP loop position
Can someone help me on this. I'm made an image uploader and i want the image to make another tr if it reach to 5 pics so it will not overflow. Here is my code:
$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='1开发者_开发知识库00' height='100'></td></tr>";
}
else
{
echo "<td><img src='user_images/".$rows['img_name'] . "' width='100' height='100'></td>";
}
}
mysql_close();
E.g. by using the 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>';
It uses the modulus operator, but in addition it checks that a has been opened.
$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();
$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; ?>
精彩评论