Sunday, January 29, 2012

How to increase the number of something using sessions?


I want the session increase more number every time I click on a button. The problem is I can not get it to increment. Seemed like it get the same value all the time. The script is below.




$no = 1;
session_start();

session_register("sess_id");
$_SESSION['sess_id'][]=$no;

$no++;

5 comments:

  1. Your question is a bit vague, but I think you're looking for something along the lines of:

    session_start();
    if (isset($_SESSION['number'])) { /* If there is already a value set */
    $_SESSION['number']++; /* Increment by 1 */
    }
    else { /* If there is no value set, ie the user is clicking the button for the first time */
    $_SESSION['number'] = 1; /* Set to 1 */
    }

    ReplyDelete
  2. All you need to do is increment the value in the $_SESSION array:

    session_start();
    $_SESSION['no'] = empty($_SESSION['no']) ? 0 : $_SESSION['no'];
    $_SESSION['no'] += 1;

    ReplyDelete
  3. Using session_register is DEPRECATED as of PHP 5.3.0

    <?php
    session_start();
    $_SESSION['count']=(isset($_SESSION['count']))?$_SESSION['count']+1:0;
    ?>

    ReplyDelete
  4. The main issue is how you're incrementing your variable. PHP does not default to assigning variables by reference, so $_SESSION['sess_id'][] = $no; is actually assigning by value (in addition to indexing the variable as an integer). Your subsequent call $n++ won't alter the value stored in your PHP session.

    What I think you want is to assign by reference, e.g.

    $no = 1;
    session_start();
    $_SESSION['your_session_var_name'] =& $no; // value is '1'

    $no++; // $no is now '2'
    echo $_SESSION['your_session_var_name']; // outputs '2'

    ReplyDelete
  5. Do not use session_register anymore, just use the $_SESSION array.

    session_start();
    if(!isset($_SESSION['sess_id'])) $_SESSION['sess_id'] = 0;
    $_SESSION['sess_id']++;

    ReplyDelete