Skip to content
Advertisement

How to increase/decrease the number in $_GET variable link?

I have a PHP page that utilizes a $_GET variable, “link”, to display a specific image on the page. My PHP page URLs look like “website.com/page.php?link=1”

PHP Code:

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

I want to add ‘Next’ and ‘Previous’ buttons on this page, which will go to the next/previous $link URL when clicked.

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

What should I put as the href in order to achieve this? Basically, I want it to be “$link -1” for previous and “$link +1” for next.

Thanks in advance for the help!

Advertisement

Answer

Assuming your images will always be image1.jpg, image2.jpg, image3.jpg etc, you can achieve what you’re looking for like this:

Note: I used PHP only just so it’s easier to follow the logic

<?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>";
}
?>
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement