PHP:Echo IMG标记有两个不同的ID

时间:2015-04-14 21:25:31

标签: php html

我需要打印到一个写入的两个IMG标签但是使用不同的ID只使用一个行回送代码?

示例:

$sql = mysql_query("SELECT * FROM products ORDER BY pid");

while ($data = mysql_fetch_array($sql)){
 echo "<div class=\"item\">\n";
 echo "<div>";
 echo "<img src=\"img/products/".$data['photo']."\" />";
 echo "</div>";
 echo "</div>\n";
}

输出:

<div class="item">
<div>
<img src="img/products/1.png" />
<img src="img/products/2.png" />
</div>
</div>

2 个答案:

答案 0 :(得分:1)

你只需要在循环外移动外部html。这样,在每行打印图像标签时仅打印一次。 例如:

$sql = mysql_query("SELECT * FROM products ORDER BY pid");
echo "<div class=\"item\">\n";
echo "<div>";
while ($data = mysql_fetch_array($sql)){
 echo "<img src=\"img/products/".$data['photo']."\" />";
}
echo "</div>";
echo "</div>\n";

输出:

<div class="item">
<div>
<img src="img/products/1.png" />
<img src="img/products/2.png" />
</div>
</div>

答案 1 :(得分:-1)

在while循环中添加一个计数器,用于为图像提供不同的ID。

   $i=1;
    while ($data = mysql_fetch_array($sql)){
     echo "<div class=\"item\">\n";
     echo "<div>";
     echo "<img id='img".$i."' src=\"img/products/".$data['photo']."\" />";
     echo "</div>";
     echo "</div>\n";
    $i++;
    }