问题描述:

I'm trying to echo out data from my database using PDO and have it create a table with 4 columns and as many rows until there is no more data to echo out. Right now there should be 16 items in the database, so I should have 4 rows, but I can't get my data to echo in that format, 4 columns and 4 rows. It just echoes out in one rows and 16 columns. Thanks in advance for the help.

Here is the php code I have so far:

echo "<table>";

for($x = 0;$x<1;$x++){

foreach($result as $row){

echo "<td>{$row['question_name']}</td>";

}

echo "</tr>";

}

echo "</table>";

网友答案:

HTML tables are really bad for this. Instead, try using a plain list and use CSS to turn it into a grid

?>
<ul class="grid">
    <?php foreach ($result as $row) : ?>
        <li><?= htmlspecialchars($row['question_name']) ?></li>
    <?php endforeach ?>
</ul>

and some CSS

.grid {
    list-style: none;
    width: 512px;
}

.grid li {
    float: left;
    width: 128px;
    height: 128px;
}

If you really want to persist with the table approach, you need to detect every fourth entry and close / re-open a table-row, eg

?>
<table class="grid">
    <tr>
    <?php foreach ($result as $i => $row) : ?>
        <td><?= htmlspecialchars($row['question_name']) ?></td>
        <?php if (($i + 1) % 4 == 0) : ?></tr><tr><?php endif ?>
    <?php endforeach ?>
    </tr>
</table>
相关阅读:
Top