首页 > 解决方案 > 如何增加/减少 $_GET 变量链接中的数字?

问题描述

我有一个 PHP 页面,它利用 $_GET 变量“链接”在页面上显示特定图像。我的 PHP 页面 URL 看起来像“website.com/page.php?link=1”

PHP代码:

$link = $_GET['link'];
if($link == 1) { $linkURL = "http://website.com/image1.jpg";}
if($link == 2) { $linkURL = "http://website.com/image2.jpg";}
if($link == 3) { $linkURL = "http://website.com/image3.jpg";}

HTML

<img src="<?=$linkURL;?>"></img>

我想在此页面上添加“下一个”和“上一个”按钮,单击时将转到下一个/上一个 $link URL。

<a class="prevBtn" href="">Previous</a>
<a class="nextBtn" href="">Next/a>

为了实现这一点,我应该把什么作为 href?基本上,我希望它是“$link -1”代表上一个,“$link +1”代表下一个。

在此先感谢您的帮助!

标签: phphtml

解决方案


假设您的图像将始终是 image1.jpg、image2.jpg、image3.jpg 等,您可以像这样实现您想要的:

注意:我只使用 PHP 只是为了更容易遵循逻辑

<?php

//Check $_GET variable exists otherwise set it to a default value = 1

if(isset($_GET['link'])) { 
    $link = $_GET['link'];
} else {
     $link = 1;
}

if($link == 1) { $linkURL = "http://website.com/image1.jpg";}
if($link == 2) { $linkURL = "http://website.com/image2.jpg";}
if($link == 3) { $linkURL = "http://website.com/image3.jpg";}

// Set variables for the previous and next links
$prev = $link-1;
$next = $link+1;

//Display your image    
echo "<img src='".$linkURL."'></img>";

//Only show the previous button if it's NOT the first image
if($prev!=0){
     echo "<a class='prevBtn' href='http://website.com/page.php?link=".$prev."'>Previous</a>";
}

//Only show the next button if it's NOT the last image
if($next<=3){
    echo "<a class='nextBtn' href='http://website.com/page.php?link=".$next."'>Next</a>";
}
?>

推荐阅读