2

我正在尝试从数据库中显示我的产品。我正在尝试使用 if 4%=0 来拆分它,但我无法让它连续显示 4 个项目。

这是我的代码:

<table>
<tr>
     <?php
        include "connect_to_mysql.php";
        $split = 0;
        $display_all = mysql_query("SELECT * FROM products 
            ORDER BY FIELD(category, 'ipad','iphone','others')");
        while($row=mysql_fetch_array($display_all)) {
        $id = $row['id'];
        $product_code = $row['product_code'];
        $title = $row['title'];
        $price = $row['price'];
        $split++;   
        if ($split%4==0){
        echo '</tr><tr>';   
        }
        ?>
        <td>
        <table class="normal_text" align="center">
        <tr>
        <td><a href="product.php?product_id=<?php echo $id?>">
            <img width="200px" height="133px" src="products/<?php echo $product_code?>.jpg" />
            </a></td>
        </tr>
        <tr>
        <td align="center" style="font-weight:bold"><?php echo $title;?></td>
        </tr>
        <tr>
        <td align="center">$<?php echo $price;?></td>
        </tr>
        </table>
        </td>
        <?php
        }
        ?>
</tr>
</table>
4

3 回答 3

2

您之前已经获得了 PHP 逻辑,而不是HTML 表格输出中。
尝试像这样重新组织:

<?php
include "connect_to_mysql.php";
$split = 0;
$display_all = mysql_query("SELECT * FROM products 
    ORDER BY FIELD(category, 'ipad','iphone','others')");
?>
<table class="normal_text" align="center">
<tr>
<?php
while($row=mysql_fetch_array($display_all)) {
    $id = $row['id'];
    $product_code = $row['product_code'];
    $title = $row['title'];
    $price = $row['price'];

    // output product details -- note use of quotes to include PHP vars
    $rowHTML = "<td><a href='product.php?product_id=$id'>";
    $rowHTML .= "<img width='200px' height='133px' src='products/$product_code.jpg' />";
    $rowHTML .= "</a><br/>";
    $rowHTML .= "<strong>$title</strong>";
    $rowHTML .= "$price</td>";
    echo $rowHTML;

    $split++;   
    if ($split%4==0){
        echo '</tr><tr>';
    }
}
?>
</tr>
</table>
于 2012-06-16T08:33:17.110 回答
1
while($row=mysql_fetch_assoc($display_all)) {
    $id = $row['id'];
    $product_code = $row['product_code'];
    $title = $row['title'];
    $price = $row['price'];
    if ($split % 4 === 0) echo "\n<tr>";
?>

// 这里只写<td>代码</td>。没有<tr>和没有</table>

<?php
 if ($split % 4 === 3) echo "</tr>"; 
  $split++;
 }
?>

您同时开始和结束,然后为每个放置表。你想从什么时候开始,<tr>什么时候%4==0结束。</tr>%4==3

于 2012-06-16T08:39:22.393 回答
-1

而不是使用模数 ( %),只需添加第二个名为 的变量$cols,将其分配给所需的列数,然后进行比较。例如:

    $rows = 1;
    $cols = 4;

    $display_all = mysql_query("SELECT * FROM products ORDER BY FIELD(category, 'ipad','iphone','others')");

    while($row=mysql_fetch_array($display_all)) {
    $id = $row['id'];
    $product_code = $row['product_code'];
    $title = $row['title'];
    $price = $row['price'];
    $split++;   
    if ($rows==$cols){
        echo '</tr><tr>'; 
        $rows = 1;
    }
于 2012-06-16T08:36:10.757 回答