我正在尝试在HTML表中显示具有特定类别的数据库中的所有产品。但是我不确定如何将表限制为仅三列。

这是我的代码:

<table>
    <?php
  $catagory=$_GET["q"];


$con = mysql_connect("localhost","cl49-XXX","XXX");
if (!$con)
  {
   die('Could not connect: ' . mysql_error());
   }

mysql_select_db("cl49-XXX", $con)or die( "Unable to select database");


$result=mysql_query("SELECT * FROM products WHERE catagory  = '$catagory' ")or die('You need enter a catagory ' );

  for ($i = 0; $i < mysql_num_rows($result); $i++)
    {
        $row = mysql_fetch_array($result);

        $prodname = $row['prodname'];
        $prodID = $row['prodID'];
        if ($i % 5 == 0 || $i == 0) {
            echo "<tr>";
        }
        echo "
        <td>
            <b>$prodname </b><br />
            Product ID: $prodID<br />
            <img src='/userpics/$prodID.jpg' height='200' width='200'>
        </td>";

        if ($i % 3 == 0 || $i == (mysql_num_rows($result)-1)) {
            echo "</tr>";
        }
    }
    ?>
<table>


我正在等待在同一“单元格”中全部显示prodID,prodtitle和图片,但只有三列(每行三个产品)。

我该怎么做呢?

最佳答案

echo "<tr>"; // first row beginning
for ($i = 1; $i <= mysql_num_rows($result); $i++)
{
    $row = mysql_fetch_array($result);

    $prodname = $row['prodname'];
    $prodID = $row['prodID'];

    echo "
    <td>
        <b>$prodname </b><br />
        Product ID: $prodID<br />
        <img src='/userpics/$prodID.jpg' height='200' width='200'>
    </td>";

    if ($i % 3 == 0) {
        echo "</tr> <tr>"; // it's time no move to next row
    }
}
echo "</tr>"; // last row ending


请注意,$ i现在从1开始,并且在num_rows的<=而不是<时循环。

关于php - PHP数组到HTML表中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18017820/

10-12 13:21