Creating a dynamic table with PHP

后端 未结 2 484
南笙
南笙 2020-12-09 23:50

I\'m trying to make a dynamic table with PHP. I have a page which displays all the pictures from a database. I need the table to be of 5 columns only. If more than 5 pictur

相关标签:
2条回答
  • 2020-12-09 23:52
    $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>
    
    0 讨论(0)
  • 2020-12-09 23:57
    $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>";
    
    0 讨论(0)
提交回复
热议问题