2012-09-01 29 views
4

只是想知道,如果有人能夠給我一個手爲每個循環面露PHP數據庫PHP三列的表...從產品

我公司目前擁有的我都回顯出來一個產品的表每個表格都有75%的時間,但是我希望它成爲三列表格。我不介意例如有4款產品在產品表和它的第一列,並在未來2是空等

當前如下代碼...

<?php 

if($results && mysql_num_rows($results) > 0){ 
?> 

    <?php 
    $i = 1; 
    while($row = mysql_fetch_assoc($results)){ 
     $i++; 
?><table width="750"> 
<tr> 
    <td id="topbottom" width="220px"><a href="products.php?id=<?php echo($row['productId']); ?>"/><img src="images/<?php echo($row['imageName']); ?>" width="220px"/></a></td> 
    <td id="pad"> 
    <h1><?php echo($row['productName']); ?></h1> 
    <br> 
    <h2><?php echo($row['productType']); ?></h2> 
    <br> 
    <h3> &pound;<?php echo($row['productPrice']); ?></h3> 
    <br> 
    <?php echo($row['productDesc']); ?> 
    <br /><br /> 
    <a href="products.php?id=<?php echo($row['productId']); ?>"/><img src="images/findout.png"/></a> 

    </td> 
    </tr></table><hr color="#6c3600" width="75%" /> 
<?php 
    } 
?> 


<?php 
} else { 
    echo("<p>No items found</p>"); 
} 
?> 

回答

2
<table width="750"> 

<?php 

if($results && mysql_num_rows($results) > 0){ 
?> 

    <?php 
    $i = 0; // Set this to 0, since php is 0 based 
    $cols = 3; // Number of cols you want 
    while($row = mysql_fetch_assoc($results)){ 
     // Use the modulus operator to see if i is an even multiple of $cols 
     // If it is then we need to open a new table row 
     if($i % $cols == 0) 
     { 
      echo '<tr>'; 
     }  
?> 
    <td id="topbottom" width="220px"><a href="products.php?id=<?php echo($row['productId']); ?>"/><img src="images/<?php echo($row['imageName']); ?>" width="220px"/></a></td> 
    <td id="pad"> 
    <h1><?php echo($row['productName']); ?></h1> 
    <br> 
    <h2><?php echo($row['productType']); ?></h2> 
    <br> 
    <h3> &pound;<?php echo($row['productPrice']); ?></h3> 
    <br> 
    <?php echo($row['productDesc']); ?> 
    <br /><br /> 
    <a href="products.php?id=<?php echo($row['productId']); ?>"/><img src="images/findout.png"/></a> 

    </td> 
    <?php 

    $i++; 
    // Same as above but we want to close the table row after $cols 
    if($i % $cols == 0) 
    { 
     echo '</tr>'; 
    } 
    ?> 
<?php 
    } 
?> 

</table><hr color="#6c3600" width="75%" /> 


<?php 
} else { 
    echo("<p>No items found</p>"); 
} 
?> 

關鍵的事情,尋找:

設置$i0因爲PHP使用基於0的數組

建立一個變種稱爲$cols其人無法輕鬆更改列數

使用%(模數)運算符來查找數字是否爲偶數倍的列,以便在正確的位置動態添加<tr>標記。

+0

像夢一樣工作。 謝謝Brombomb! –