Add variable in session variable in PHP?

22,542

Solution 1

You need to make sure you used session_start();

page1.php

<?php
session_start();

$product = 0;
$_SESSION['product_number'.$product] = true;

?>

page2.php

<?php
session_start();
$product = 0;
if ($_SESSION['product_number'.$product]) echo 'Session variable was set!';
else echo 'It was not!';
?>

Solution 2

This may work for you:

<?
session_start();
$product = 0;
$_SESSION['product_number'] = $product;
?>
Share:
22,542
Matti Rauhiainen
Author by

Matti Rauhiainen

Updated on July 09, 2022

Comments

  • Matti Rauhiainen
    Matti Rauhiainen almost 2 years

    How do I add a variable into $_SESSION?

    $product = 0;
    $_SESSION['product_number'.$product.''] = true;
    

    It is not working.

    • Jason McCreary
      Jason McCreary over 11 years
      You should read PHP Sessions if you are just getting started.
    • Sammitch
      Sammitch over 11 years
      1. Get rid of the .'', it is useless. 2. Are you calling session_start() at the beginning of your script?
    • Paul Dessert
      Paul Dessert over 11 years
      "Is not working." Is not a valid error message.
    • khaverim
      khaverim over 11 years
      Give more information; what do you mean by 'is not working'?
    • Landon
      Landon over 11 years
      agree with @sammitch, you need to call session_start() at the top of your script if you want to use session variables at all.
    • Wolfgang Fahl
      Wolfgang Fahl over 11 years
  • John V.
    John V. over 11 years
    @MattiRauhiainen Make sure to mark this answer as "accepted" if it is what you where looking for. Green tick = accept.