繁体   English   中英

下一个/上一个链接的递增ID号

[英]increment id number for next/prev links

我有一个带有自动递增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;
}

但是使用上面的方法不会返回任何结果。 有人可以指出我正确的方向吗?

提前致谢!

    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;

需要将其更改为-

$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--;

直到执行代码行之后,才会发生增加/减少

同样,您需要翻转比较运算符(<>)。 尝试-

// 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']))if($next > intval($row['id']))将始终返回TRUE。
您应该检查的是0 < $prev < intval($row['id'])intval($row['id']) < $next < max id

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM