我有一个mysql表自动增加ID字段在它。当我循环输出到页面时,每次迭代我都用以下内容开始输出,这样我就可以通过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--;
递增/递减直到执行完这行代码后才会发生
同样,您的比较操作符(<>)需要翻转。Try -
// 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