0

I got a big problem when I tryed to work directly with session...

/* session_start(); //already tried */
if (isset($_SESSION) == false)
{
  session_start();
  $_SESSION['PDO'] = new dataBase();
  $_SESSION['Debug'] = 'Inside the isset';  
}
else
{
  $_SESSION['Debug'] = 'Outside the isset';  
}

EDIT:

session_start();
if (!isset($_SESSION['PDO'])) // the session is new
{ 
  $dbObject = new dataBase(); // store the data into the session
  $_SESSION['PDO'] = $dbObject;
  echo 'I created a session and stored some data into it';
} 
else 
{ // there is data into the session
  var_export($_SESSION);
  echo 'I have some data in the session';  
}

The output is always "I created a session and stored some data into it"

I begin to think that the problem may come from my class

class dataBase
{
  var $connLink;

  var $SERVERNAME = "127.0.0.1";
  var $PORT = "3388";
  var $USERNAME = "root";
  var $PASSWORD = "";

  function __construct()
  {
    try 
    {
        $this->connLink = new PDO("mysql:host=$this->SERVERNAME;port=$this->PORT;dbname=mydb;charset=utf8", $this->USERNAME, $this->PASSWORD);
        $this->connLink->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }
    catch (PDOException $e) 
    {
        echo 'Echec lors de la connexion : ' . $e->getMessage();
    }
  }
}

Thanks !

Alexandre Corvino
  • 199
  • 1
  • 3
  • 16

5 Answers5

2

before accessing $_SESSION you first need to initialise session using session_start(); on the top of the page

0

The $_SESSION variable does not exist until session_start() is called. This function needs to be called on each page.

Here is what you need to do :

session_start(); // start the session

if (!isset($_SESSION['PDO'])) { // the session is new
  $_SESSION['PDO'] = new dataBase(); // store the data into the session
  echo 'I created a session and stored some data into it';
} else { // there is data into the session
  echo 'I have some data in the session';  
}

On the first call on the page, the session is started and the pdo data stored into it. Then on the next calls on this page, the session is loaded from the server storage and the pdo data is in the session

Please note that sessions will not work if you use php from the command line

ᴄʀᴏᴢᴇᴛ
  • 2,939
  • 26
  • 44
0
session_start();

if (!isset($_SESSION['PDO']))
{
  $_SESSION['PDO'] = new dataBase();
  $_SESSION['Debug'] = 'Inside the isset'; 
}
else
{
  $_SESSION['Debug'] = 'Outside the isset';  
}

you have something like this ?

EDIT :

if(!isset($_SESSION['test']))
{
    $obj = new stdClass();
    $_SESSION['test'] = $obj;
}
else{
    var_export($_SESSION);
}

try this then

Frankich
  • 842
  • 9
  • 19
0

use session_start() before $_SESSION Click here for more details .....

Er Sahaj Arora
  • 852
  • 8
  • 13
0

Finally I decided to never create my object and to use it only by static function Like dataBase::connectDB(); etc ...

Alexandre Corvino
  • 199
  • 1
  • 3
  • 16