Page 1 of 1

Newbie Q: Increment of 1 in a variable by clicking a link?

Posted: Sat Mar 01, 2008 12:44 am
by cmarc
Hi,

I'm an absolute newbie in PHP and my "problem" is probably not an exciting one for most people here, but I would appreciate it very much if someone could provide me with a solution.

I'm not even sure I can explain my problem properly (Danish newbie.. :-)), but I will try.

Basically I'm trying to figure out how to make a good page navigation system so that no matter how many pages you have, you will stay on the index page the whole time, but with different main content.

I got an idea to do this if I can manage to make an increment of 1 in a variable when a link is clicked.

In another link I want to make an increment of 10 in the same variable.

This is what I tried so far:

<a href="index.php?sidetillaeg=1">add 1</a>

and

<a href="index.php?sidetillaeg=10">add 10</a>

The plan is to make 2 more links subtracting 1 and 10 instead of adding them.

In the index.php file I then used...

$sidestyrer = $_GET["sidetillaeg"];

...to make sure that PHP has the correct number (1 or 10) in a variable it understands, here named $sidestyrer.

The next thing I do is this:

$page = $page + $sidestyrer;

The $page variable always holds the number of the page I want to output.

All this actually works for me, but only the first time I click a link! After that any click on the same link will output the same page as previous.

And I suppose the reason must be that the URL becomes "index.php?sidetillaeg=1" where it should actually be "index.php?"?

How can I make a variable increase with a value of 1 everytime I click a certain link and then send the user to the same page?

All help is appreciated, thank you.

- cmarc

Re: Newbie Q: Increment of 1 in a variable by clicking a link?

Posted: Sat Mar 01, 2008 4:24 am
by Benjamin
Well I wouldn't go about it that way, but since your a newbie I'm not going to try to convince you to use front controllers or url mapping.

So with that said:

Code: Select all

 
# start a session
session_start();
 
# be sure the integer is set to something
$_SESSION['integer'] = (empty($_SESSION['integer'])) ? 1 : $_SESSION['integer'];
 
# process any changes to the integer if it's in the $_GET request
if (!empty($_GET['int']))
{
    # i canz haz validz intz?
    # regex: a - (zero or one) times followed digits (one to ten) times
    if (preg_match('#^-{0,1}[0-9]{1,10}$#', $_GET['int']))
    {
        # do the math..
        $_SESSION['integer'] += $_GET['int'];
    }
}
 
# all done
?>
<a href="page.php?int=1">Add One</a>
<a href="page.php?int=10">Add Ten</a>
<a href="page.php?int=-1">Subtract One</a>
<a href="page.php?int=-10">Subtract Ten</a>