php - MySQL-PHP : Display Results In Table Rows (5 results per row)

标签 php mysql

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

图像1-图像2-图像3-图像4-图像5

(新行)

图像6-图像7-图像8-图像9-图像10

我如何使用 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 行...

最佳答案

    $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>';  

关于php - MySQL-PHP : Display Results In Table Rows (5 results per row),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20333961/

相关文章:

php - Doctrine 2 : Page, block 、策略模式和相关实体

php - 在 Doctrine 中使用 LIMIT 进行子查询

mysql - 将带有子查询的原始查询转换为 Eloquent 查询

使用 Oracle Instant 客户端 10.2.0.4 使用 PDO-OCI 驱动程序编译 PHP 5.4

php - 在 woocommerce_loop_add_to_cart_link Hook 后添加Quantity_inputs而不调用它

php - 在哪里可以找到触发 unset() 垃圾回收的 "low memory"和 "free CPU cycles"调用?

php - 如何使用 php 和 mysql 创建一个订单消息系统

mysql - SQL:添加唯一索引和添加唯一索引之间的区别?

mysql - 如何使用虚拟实体数据预填充数据库?

c# - 如何增加来自 c# 应用程序的 mysql 连接的连接超时?