Reputation: 17
I am trying to make a basic gallery of sorts to put on a web page. This is my code so far:
<?
if($_REQUEST['cho'] == 'next')
{
$img = $img + 1;
}
else
if($_REQUEST['cho'] == "previous")
{
$img = $img - 1;
}
else
if(!$_REQUEST['cho'] == 'next')
{
if(!$_REQUEST['cho'] == "previous")
{
$img = 1;
}
}
?>
<center>
<table border =1>
<tr>
<td>
<form action="image.php" method="post">
<input type="submit" name="cho" value="previous">
</form>
</td>
<td>
<form action="image.php" method="post">
<input type="submit" name="cho" value="next">
</form>
</td>
</tr>
<BR>
<table border =1>
<tr>
<td>
<img src="<? echo($img . ".jpg"); ?>">
</td>
</tr>
</table>
It is all saved in a file called image.php
.
I can view the first image (named 1.jpg, all images are named like this.) and pushing the next button displays the second. But from then on pushing the previous
button tries to load -1.jpg
and next
just loads the current image.
Thanks.
Upvotes: 0
Views: 106
Reputation: 611
use php sessions, or save it and pass it in a query string (?img=3 instead of ?cho=next, and auto compute the next and previous link)
<?php
$totalImages = 5;
session_start();
if (!isset($_SESSION['currentImage'])) {
$_SESSION['currentImage'] = 1;
}
if($_REQUEST['cho'] == 'next')
{
if($_SESSION['currentImage'] === $totalImages) {
$_SESSION['currentImage'] = 1;
} else {
$_SESSION['currentImage']++;
}
}
elseif($_REQUEST['cho'] == "previous")
{
if($_SESSION['currentImage'] === 1) {
$_SESSION['currentImage'] = $totalImages;
} else {
$_SESSION['currentImage']--;
}
}
?>
Upvotes: 0
Reputation: 328
This has to do with the scope of the variable $img. You currently have it being declared in each if statement. You should declare the variable before any looping so the value is persistent.
Take a look here:
<?
$img = 1;
if($_REQUEST['cho'] == 'next')
{
$img = $img + 1;
}
else
if($_REQUEST['cho'] == "previous")
{
$img = $img - 1;
}
else
if(!$_REQUEST['cho'] == 'next')
{
if(!$_REQUEST['cho'] == "previous")
{
$img = 1;
}
}
?>
Upvotes: 1