[英]PHP Increment number, each time a new div is created
Basically I have a PHP script that creates a div for each item in the database, but I want to have a "rank" number in each div created, ie:基本上我有一个 PHP 脚本,它为数据库中的每个项目创建一个 div,但我希望在创建的每个 div 中都有一个“排名”数字,即:
-----------------
Rank: 1 < div 1
-----------------
Rank: 2 < div 2
-----------------
Rank: 3 < div 3
-----------------
And so on..等等..
Here's my current code...这是我当前的代码...
while($row = mysql_fetch_array($result)) {
$name = stripslashes($row['name']);
$description = stripslashes($row['description']);
$votes = stripslashes($row['votes']);
$id = ($row['id']);
$link = ($row['link']);
$rank = 0;
?>
<div class="site" id="site">
<u><center>
<strong><a href="<?php echo $link ?>" target="_blank"><?php echo $name; ?></a></strong></u>
</font></center>
<p>Rank:<?php echo $rank++ ; ?></p>
<p><b><?php echo $description; ?></b><br />
Votes:<b> <?php echo $votes; ?></b><br />
</p>
</div>
<center>
<?php
}
?>
But that doesn't work, any help would be greatly appreciated.但这不起作用,任何帮助将不胜感激。 (Also, the div's continue over multiple pages).
(此外,div 会在多个页面上继续)。
Put the $rank = 0;
把
$rank = 0;
outside of the loop.在循环之外。 Otherwise it will be always 0.
否则它将始终为 0。
You define the $rank
-variable in your loop, so in every loop-round it's defined with the value 0
.您在循环中定义
$rank
-变量,因此在每个循环中它都使用值0
定义。 Define the counter-variable outside the loop and increase it in the loop.在循环外定义反变量并在循环中增加它。
Rank need to be outside the loop or you will reset it to 0 everytime排名需要在循环之外,否则您每次都会将其重置为 0
$rank = 0;
while($row = mysql_fetch_array($result)) {
$name = stripslashes($row['name']);
$description = stripslashes($row['description']);
$votes = stripslashes($row['votes']);
$id = ($row['id']);
$link = ($row['link']);
?>
<div class="site" id="site">
<u><center>
<strong><a href="<?php echo $link ?>" target="_blank"><?php echo $name; ?></a></strong></u>
</font></center>
<p>Rank:<?php echo $rank ; ?></p>
<p><b><?php echo $description; ?></b><br />
Votes:<b> <?php echo $votes; ?></b><br />
</p>
</div>
<center>
<?php
$rank++;
}
?>
Additional for comment:补充评论:
Use an offset for that, for example例如,为此使用偏移量
$result_per_page = 5; // this is the number of result you show per page
$offset = isset($_GET['id'])? (int)$_GET['id'] : 1;
$rank = $offset * $result_per_page;
$rank
needs to be defined outside of the while
statement. $rank
需要在while
语句之外定义。 Every time it loops it's resetting to zero.每次循环它都会重置为零。 Also, increment
$rank
elsewhere - it makes the code slightly more robust and intelligible.此外,在其他地方增加
$rank
- 它使代码更加健壮和易懂。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.