在PHP中为表创建一个while循环

时间:2014-05-20 15:25:45

标签: php mysql html-table

我正在建立一个销售产品的网站,我有一张桌子可以展示像" square"表格类型价格图片信息购买按钮

我是这类代码的新手,我无法理解如何运作。我在这里有example我想要的东西。我知道它使用AJAX,但我只想要一个代码/解释才能使这种类型的os" square"表格 我在 MySQL数据库中的产品,因此我自动添加了更多产品,而另一个" square"。

这是我的PHP代码:

<?php
    //Conection to DataBase//
    $link=mysqli_connect('localhost','root','','produtos');
    if(mysqli_connect_errno())
    exit("falhou a conexão ao mysql:".mysqli_connect_error());

    //Codification Type//
    mysqli_query($link,"set names utf8");

    //Select from DataBase//
    $query="Select * FROM fornos";
    $result = mysqli_query($link, $query);
    if (!$result)
        exit("Error in query SELECT: " . mysqli_error($link));
    $fornos = mysqli_fetch_assoc($result);
    $imagem = $fornos['file'];
    $preco = $fornos['preco'];

    // Termina a ligação à Base de Dados
    mysqli_close($link);

?>

这是我的桌位:

<table id="tabela1">
                    <?php
                        while ($fornos = mysqli_fetch_assoc($result))
                        {
                            echo"<tr>";
                            echo"<td class='products_td'> $preco </td>";
                            echo"</tr>";
                            echo"<tr>";
                                echo"<td class='products_td'><img class='img_product' src='images/fornos/$imagem'></td>";
                            echo"</tr>";
                            echo"<tr>";
                                echo"<td class='products_td'>Informações</td>";
                            echo"</tr>";
                            echo"<tr>";
                                echo"<td class='products_td_buy'>Comprar</td>";
                            echo"</tr>";

                        }
                    ?>
</table>

1 个答案:

答案 0 :(得分:0)

tr表示表格行。您要为每个项目的每个细节添加一个新行。您希望使用基本模数运算符每隔4个项目创建一个新行。见这里:

<?php
    $query="Select * FROM fornos";
    $result = mysqli_query($link, $query);
    if (!$result)
        exit("Error in query SELECT: " . mysqli_error($link));
?>
<table id="tabela1">
   <tr>
   <?php
   $i = 0;
   while ($fornos = mysqli_fetch_assoc($result)):
      if($i > 0  && $i % 4 == 0): 
      /* this line above is what creates a new row every 4th. */
      ?>
      </tr><tr>
      <?php endif; ?>

      <td class='products_td'>
        <?php echo $fornos['preco']; ?><br>
        <img class='img_product' src='images/fornos/<?php echo $fornos['file']; ?>'><br>
        Informações<br>
        Comprar
      </td>

    $i ++; endwhile; ?>
   </tr>
</table>

这是一个基本想法。