我是新来的,需要一些帮助。我正在做一个网络开发课程并且有一个我需要帮忙的作业。
基本上,我想发送一个选择9个随机记录的查询,并将结果显示为3x3表。
到目前为止,这是我的代码:
<div id="productgrid">
<?php
$query = mysqli_query($conn, "SELECT * FROM products
ORDER BY RAND()
LIMIT 9");
?>
<h2>Featured Products</h2>
<table>
<?php
while($products = mysqli_fetch_array($query)){
$file = $products['prod_img'];
$pid = $products['prod_id'];
$product_price = $products['prod_price'];
$image_id = $products['prod_id'];
$desc = $products['prod_desc'];
?>
<tr>
<div class="bigred">
<td class="bigred">
<?php echo '<b>'. "$product_price".'</b>'; ?>
</td>
</div>
</tr>
<tr>
<td>
<img src="<?php echo $file ?>" height = "150px" width="150px"/><br />
</td>
<div class="smallblack"
</tr>
<tr>
<td class = "smallblack">
<?php echo '<b>' . "$desc".'</b>'; ?>
</td>
</tr>
</div>
<?php } ?>
我可以让它生成9个随机图像,但它将它们全部直接放在一个长列中。有没有办法可以让它们显示3行3?
如果这是一个愚蠢的问题,我道歉,但我只是开始并感谢你的帮助。
谢谢:)
Pic附加为样本
答案 0 :(得分:0)
你应该更改你的表格并使用3 <td>
个标签而不仅仅是那个标签,如此......
<table>
<tr>
<?php
$counter = 0; // Needs to be outside of the loop...
while($products = mysqli_fetch_array($query)){
$file = $products['prod_img'];
$pid = $products['prod_id'];
$product_price = $products['prod_price'];
$image_id = $products['prod_id'];
$desc = $products['prod_desc'];
?>
<td class="bigred">
<?php echo '<b>'. "$product_price".'</b>'; ?>
<img src="<?php echo $file ?>" height = "150px" width="150px"/><br />
<?php echo '<b>' . "$desc".'</b>'; ?>
</td>
<?php
// Check to see if you have looped through three times and close the <tr> tag.
if($counter % 3 === 0) {
echo '</tr><tr>';
}
$counter++
?>
</table>
如果有超过9个图像,那么它将继续创建表格行和单元格,你需要更多的逻辑来处理它,但是,这应该适用于9个图像。
更优雅的方法是使用<div>
标签和浮点数,但由于你已经在使用表格,我将其格式化。
答案 1 :(得分:0)
<?php
// A counter which is incremented by one for each product row
// in the loop below.
$i = 0;
echo "<table>\n";
echo "<tr>\n";
while ($product = mysqli_fetch_array($query)) {
// Re-open HTML row, if $i is divisible by 3
if ($i++ % 3 == 0) {
echo "</tr><tr>\n";
}
// Escape the `src` attribute value as appropriate, according to the
// logic of your app. This is just a sample.
$img_src = htmlspecialchars($product['prod_img']);
echo <<<HTML
<td>
<div><img src="{$img_src}"/></div>
<div>{$product['prod_desc']}</div>
<!-- Put the rest of the fields here -->
</td>
HTML;
}
// Add cells for the rest of the columns (if any)
while ($i++ % 3 != 0) {
echo "<td></td>\n";
}
echo "</tr>\n";
echo "</table>\n";
?>
P.S。:我建议使用模板引擎,如Smarty或Twig。借助模板引擎,您可以使标记更具可读性和可维护性。