5

我正在尝试用 PHP 制作一个动态表。我有一个页面显示数据库中的所有图片。我需要表格只有 5 列。如果返回的图片超过 5 张,则应创建一个新行并继续显示其余图片。

有人可以帮忙吗?

代码在这里:主页中的代码:-

    <table>
    <?php
        $all_pics_rs=get_all_pics();
        while($pic_info=mysql_fetch_array($all_pics_rs)){
        echo "<td><img src='".$pic_info['picture']."' height='300px' width='400px' /></td>";
            } 
?>
</table>

get_all_pics() 函数:

$all_pics_q="SELECT * FROM pics";
        $all_pics_rs=mysql_query($all_pics_q,$connection1);
        if(!$all_pics_rs){
            die("Database query failed: ".mysql_error());
        }
        return $all_pics_rs;

此代码正在创建单行。我想不出我怎么能得到多行......!

4

2 回答 2

12
$maxcols = 5;
$i = 0;

//Open the table and its first row
echo "<table>";
echo "<tr>";
while ($image = mysql_fetch_assoc($images_rs)) {

    if ($i == $maxcols) {
        $i = 0;
        echo "</tr><tr>";
    }

    echo "<td><img src=\"" . $image['src'] . "\" /></td>";

    $i++;

}

//Add empty <td>'s to even up the amount of cells in a row:
while ($i <= $maxcols) {
    echo "<td>&nbsp;</td>";
    $i++;
}

//Close the table row and the table
echo "</tr>";
echo "</table>";

I haven't tested it yet but my wild guess is something like that. Just cycle through your dataset with the images and as long as you didn't make 5 <td>'s yet, add one. Once you reach 5, close the row and create a new row.

This script is supposed to give you something like the following. It obviously depends on how many images you have and I assumed that 5 (defined it in $maxcols) was the maximum number of images you want to display in a row.

<table>
    <tr>
        <td><img src="image1.jpg" /></td>
        <td><img src="image1.jpg" /></td>
        <td><img src="image1.jpg" /></td>
        <td><img src="image1.jpg" /></td>
        <td><img src="image1.jpg" /></td>
    </tr>
    <tr>
        <td><img src="image1.jpg" /></td>
        <td><img src="image1.jpg" /></td>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
        <td>&nbsp;<td>
    </tr>
</table>
于 2011-10-25T07:23:04.160 回答
2
$max_per_row = 5;
$item_count = 0;

echo "<table>";
echo "<tr>";
foreach ($images as $image)
{
    if ($item_count == $max_per_row)
    {
        echo "</tr><tr>";
        $item_count = 0;
    }
    echo "<td><img src='" . $image . "' /></td>";
    $item_count++;
}
echo "</tr>";
echo "</table>";
于 2011-10-25T07:22:42.430 回答