tags:

views:

48

answers:

4

I want it to increment and decrement the value in $_SESSION['selection'].
Mousedown on next form results in: "The session is 1".
Mousedown on previous form results in "The session is -1".

Here is the code:

  <?php

    if (isset($_POST['next'])) {
      displaynext();
    }
    else if (isset($_POST['previous'])) {
      displayprevious();
    }
    else {
      session_start();
      echo "session started";
      $_SESSION['selection'] = 1;
    }

    function displaynext() {
      $_SESSION['selection'] = $_SESSION['selection'] + 1;
      echo "The session is $_SESSION[selection]";
    }

    function displayprevious() {
      if ($_SESSION['selection'] != 1) {
        $_SESSION['selection'] = $_SESSION['selection'] - 1;
      }
      echo "The session is $_SESSION[selection]";
    }

    ?>

    <form action="<?=$_SERVER['PHP_SELF'];?>" method="post">
      <input type="submit" name="previous" value="Previous">
    </form>

    <form action="<?=$_SERVER['PHP_SELF'];?>" method="post">
      <input type="submit" name="next" value="Next">
    </form>
A: 

Make sure you're using session_start() on every page you use your session on.

+4  A: 

Put the session_start() call on the beginning of your file; right after the <?php open tag. You also need to do that on every script that you plan to use sessions.

By the way, instead of writing:

$_SESSION['selection'] = $_SESSION['selection']-1;
$_SESSION['selection'] = $_SESSION['selection']+1;

You can use

$_SESSION['selection']--;
$_SESSION['selection']++;

Read: Increment/Decrement operators

NullUserException
excellent thank you problem solved
tylercomp
@tylercomp Don't forget to mark an answer as 'accepted' when it answered your question, by clicking the check icon left of the image.
Aistina
A: 

Put the session_start call to the beginning of your code, outside of any conditions.

session_start needs to be called in every script you're using the session in, not just at the very beginning (ie. the first pageload).

Maerlyn
A: 

You're not calling session_start when moving between pages. Move the call to before the if statements, like this:

session_start();
if(isset($_POST['next'])) {
  displaynext();
} else if(isset($_POST['previous'])) {
  displayprevious();
} else {
  echo "session started";

  $_SESSION['selection'] = 1;
}
Aistina