2013-02-24 46 views
2

我想在表中显示来自数据库的4个图像(2 * 2)我知道该怎么做。但我也有特殊情况(如果图片少于4张,它会显示默认图片,以显示4张图片)在while循环中设计表

我在while循环中管理它。如果有4张图像没有问题,它可以正常工作,但当图像较少时(这意味着默认图像总共可以完成4张图像),它不起作用。我无法弄清楚如何做到这一点。

任何帮助?

<table> 
<tr> 
<?php        
$todisplay = 4; 

$query = mysql_query("select * from Images where Country_ID=$co_id LIMIT 0,4;"); 

while ($row = mysql_fetch_array($query)) { 
$x++; 
echo "<td><img src='".$row['I1_Th'] . "'/></td>"; 
$displayed_number++; 
if ($x % 2==0) { 
echo "</tr><tr>";} 
} 

echo str_repeat("<td> 
<img src='images/png/defthumb.png'> </td>", $todisplay-$displayed_number); 
?> 
</tr></table> 

回答

1

而不是循环查询返回的行,为什么不循环四次并试图获取一行?

<table> 
<tr> 
<?php        
$tablerows = 2; 

$query = mysql_query("select * from Images where Country_ID=$co_id LIMIT " + ($tablerows * 2) + ";"); 

for ($x = 1; $x <= ($tablerows * 2); $x++) { 
    if ($row = mysql_fetch_array($query)) { 
    echo "<td><img src='".$row['I1_Th'] . "'/></td>"; 
    } else { 
    echo "<td><img src='images/png/defthumb.png'></td>"; 
    } 
    if ($x % 2==0 && $x != $tablerows * 2) { 
    echo "</tr><tr>";} 
} 
?> 
</tr></table> 
+0

谢谢!奇迹般有效。 – user1813286 2013-02-24 20:42:38

+0

您可能希望使用变量来确定行数(而不是要显示的图像数量),以确保每行总是有两列,例如,上面的更新。 – adamdunson 2013-02-24 20:50:52

2

你离它不远 - 只需创建另一个循环来完成同样的事情,但是使用默认图像。另外,$displayed_number似乎与$x保持相同的值,所以我将其删除。

<table> 
<tr> 
<?php        
$todisplay = 4; 

$query = mysql_query("select * from Images where Country_ID=$co_id LIMIT 0,4;"); 
$x = 0; 

while ($row = mysql_fetch_array($query)) { 
$x++; 
echo "<td><img src='".$row['I1_Th'] . "'/></td>"; 

if ($x % 2==0) { 
echo "</tr><tr>";} 
} 

while ($x < $todisplay) { 
$x++; 
echo "<td><img src='images/png/defthumb.png'/></td>"; 
if ($x % 2==0) { 
echo "</tr><tr>";} 
} 
?> 
</tr></table> 
+0

尊敬的都铎王朝,此代码制作2 * 2表,但默认图片再次显示下面的行4次。 – user1813286 2013-02-24 20:40:39