我有一个带有自动递增ID字段的mysql表。当我循环输出到页面时,我使用以下内容开始每次迭代的输出,所以我可以通过url中的锚点返回它:
// after query and while loop
<a name="'.$row['id'].'"></a>
我想做的是在每次迭代中都有一个next / prev样式链接,它获取$ id,将其递增1并解析一个链接,如果有next或prev $ id,就像这样:
// query then loop
while ($row = mysql_fetch_array($result)) {
// increment $id to create var for NEXT link
$n = intval($row['id']);
$next = $n++;
// decrement $id to create var for PREV link
$p = intval($row['id']);
$prev = $p--;
// output PREV link
if($prev > intval($row['id'])) {
echo '<a href="page.php#'.$prev.'">Previous</a> | ';
} else {
echo 'Previous | ';
}
// output NEXT link
if($next < intval($row['id'])) {
echo '<a href="page.php#'.$next.'">Next</a>'.PHP_EOL;
} else {
echo 'Next'.PHP_EOL;
}
但使用上述内容不会返回任何内容。有人能指出我正确的方向吗?
提前致谢!
答案 0 :(得分:0)
You are using post increment and decrement but you need to pree increment and decimeter
Example
$x=5;
$y=$x++;
echo $y; //Output will be 5
// increment $id to create var for NEXT link
$n = intval($row['id']);
$next = ++$n;
// decrement $id to create var for PREV link
$p = intval($row['id']);
$prev = --$p;
答案 1 :(得分:0)
需要将其更改为 -
$next = $n+1;
$prev = $p-1;
// adds/subtracts 1 from $n/$p, but keeps the same value for $n/$p
或
$next = ++$n;
$prev = --$p;
// adds/subtracts 1 from $n/$p, but changes the value for $n/$p to ++/--
请参阅http://www.php.net/manual/en/language.operators.increment.php
当你这样做时
$next = $n++;
$prev = $p--;
在执行代码行之后才会发生增加/减少
此外,您的比较运算符(&lt;&gt;)需要翻转。试试 -
// increment $id to create var for NEXT link
$n = intval($row['id']);
$next = $n+1;
// decrement $id to create var for PREV link
$p = intval($row['id']);
$prev = $p-1;
// output PREV link
if($prev < $p) {
echo '<a href="page.php#'.$prev.'">Previous</a> | ';
} else {
echo 'Previous | ';
}
// output NEXT link
if($next > $n) {
echo '<a href="page.php#'.$next.'">Next</a>'.PHP_EOL;
} else {
echo 'Next'.PHP_EOL;
}
注意 -
if($prev < intval($row['id']))
&amp; if($next > intval($row['id']))
将始终返回TRUE
您应该检查的是0 < $prev < intval($row['id'])
和intval($row['id']) < $next < max id