我构建了一个SQL查询来在网页上布置一些信息。查询效果很好。问题是while循环的每次迭代都需要CSS类自动递增1.
<div class="related-item item1">
'item1'应在下一次迭代中变为'item2',依此类推。你能给我一些想法怎么做吗?
<?php
//Construct the SQL query code
$rel = "SELECT entries.*, images.name
FROM entries, images
WHERE entries.id = blog_id
ORDER BY dateposted DESC
LIMIT 0, 3;";
//Send the query to the MySQL server
$result = mysql_query($rel);
//Pull the row as an associative array
while ($row = mysql_fetch_assoc($result)) {
echo '<div class="related-item item1">
<div class="thumbnail-wrapper">';
echo '<a href="#"><img src="./images/' . $row['name'] . '" alt="How SHAPE Reader Caitlin Flora Lost 182 Pounds"/></a></div>
<h4 class="related-article-title">
<a href="#">' . $row['subject'] . '</a>
</h4>
</div>';
} //End of while loop
?>
答案 0 :(得分:3)
保持计数器变量
$cnt = 1;
while(fetch from db) {
echo "<a class='foo{$cnt}'>click me</a>";
$cnt++;
}
产生
<a class='foo1'>click me</a>
<a class='foo2'>click me</a>
<a class='foo3'>click me</a>
etc...
但一般来说,CSS不需要这种东西。您必须为正在创建的<a>
个元素中的每个元素创建一个css规则,这会非常难看和重复。 CSS中有nth-child
支持,因此您可以编写&#34;修改&#34;它们自己基于哪个子元素(第1,第2,......第N)。
答案 1 :(得分:0)
添加一个整数并递增它......
<?php
//Construct the SQL query code
$rel = "SELECT entries.*, images.name
FROM entries, images
WHERE entries.id = blog_id
ORDER BY dateposted DESC
LIMIT 0, 3;";
//Send the query to the MySQL server
$result = mysql_query($rel);
$i = 1;
//Pull the row as an associative array
while ($row = mysql_fetch_assoc($result)) {
echo '<div class="related-item item{$i}">
<div class="thumbnail-wrapper">';
echo '<a href="#"><img src="./images/' . $row['name'] . '" alt="How SHAPE Reader Caitlin Flora Lost 182 Pounds"/></a></div>
<h4 class="related-article-title">
<a href="#">' . $row['subject'] . '</a>
</h4>
</div>';
$i++;
} //End of while loop
?>