MySQL - PHP:在表行中显示结果(每行5个结果)

时间:2013-12-02 17:12:04

标签: php mysql

我的数据库中有10张图片。我想在每个表格行显示5张图片。

image1 - 图像2 - 图像3 - 图像4 - 图像5

(新行)

image6 - image7 - image8 - image9 - image10

我如何使用MySQL和PHP做到这一点?

我的代码:

$query = mysql_query("SELECT * FROM gallery WHERE gallery_number='$gallery_number'");
while($fetch = mysql_fetch_assoc($query)){

  $image_name = $fetch['image_name'];
  $image_location = $fetch['image_location'];

  echo '<table width="960">';
  echo '<tr>';
  echo '<td>'.'<img src="'.$image_location.'" alt="'.$image_name.'"/>'.'</td>'; 
  echo '</tr>';
  echo '</table>';  
}

如您所见,结果仅显示在一个巨大的行中。我必须添加的是行需要随结果扩展。

实施例;每个结果可能超过10张图像。可能有20个图像,这意味着我需要4行......

1 个答案:

答案 0 :(得分:0)

    $query = mysql_query("SELECT * FROM gallery WHERE gallery_number='$gallery_number'");

    echo '<table width="960">';
    $i = 0; //first, i set a counter 
    while($fetch = mysql_fetch_assoc($query)){
    //counter is zero then we are start new row  
        if ($i==0){
            echo '<tr>';
        }
        //here we creating normal cells <td></td>
        $image_name = $fetch['image_name'];
        $image_location = $fetch['image_location'];
        echo '<td>'.'<img src="'.$image_location.'" alt="'.$image_name.'"/>'.'</td>';   
        //there is a magic - if our counter is greater then 5 we set counter to zero and close tr tag  
        if ($i>5){
            $i=0;
            echo '</tr>';
        };  
        $i++; //$i = $i + 1 - counter + 1
    }
    echo '</table>';