Search code examples
phpclasssession-variables

Assign session variable inside a class PHP


I am trying to assign a session var inside a class, so I can use it in an SQL query. I guess I am doing something wrong, as it doesn't seem to work (not assigning it).

class Records { 

    private $recordsTable = 'services';
    public $account;
    private $conn;

    public function __construct($db){
        $this->account = $_SESSION['account'];
        $this->conn = $db;

    }   

    public function listRecords(){
        $sqlQuery = "SELECT * FROM ".$this->recordsTable." where account='".$this->account."'";
        if(!empty($_POST["search"]["value"])){
            $sqlQuery .= 'where(id LIKE "%'.$_POST["search"]["value"].'%" ';
            $sqlQuery .= ' OR name LIKE "%'.$_POST["search"]["value"].'%" ';
            $sqlQuery .= ' OR approved LIKE "%'.$_POST["search"]["value"].'%") ';           
        }
}

If I hardcode the account name in the construct like this the query works

$this->account = "AccountName";

If I echo the $_SESSION['account'] it also prints the account

It doesn't work only if I use it like this

$this->account = $_SESSION['account'];

When I print the $sqlQuery, the account comes empty when I use $this->account = $_SESSION['account'];

So, the $_SESSION['account'] is set correctly, and the query itself is correct too

UPDATE:

Strangely, even though the $_SESSION['account'] prints the account name, if I start the session as Vishal suggested, the account start printing also inside the query


Solution

  • First check if session exists if not start session below is the code snippet

    public function __construct($db){
        if( !isset($_SESSION) ){
            session_start(); 
            $this->account = $_SESSION['account'];
        }
        $this->conn = $db;
    }