coder101
coder101

Reputation: 1605

Session variable empty after page reload

Only one of my many session variables on the cart page of my e-commerce application is getting destroyed somehow. When i add the product to the cart along with a session id, it creates an order_id(using some hash and salt logic) and puts it in session variable and when i go to the cart page it queries the DB based on both order_id and session id to fetch the products in the cart. For the first time it fetches the records, but immediately after it if i reload the page it gets an empty order_id. I'm pulling my hair on this as to how only one of the session variables is getting flushed.

It is happening on the web-server only but works totally fine on localhost

My add_to_cart.php (Session Logic)

if(empty($_SESSION['sessid'])){
    $_SESSION['sessid'] = session_id();
}

    $user_sessid = $_SESSION['sessid'];

  $ip = get_ip_address();



 if(empty($_SESSION['order_id'])){

    $ip = get_ip_address();
    $with_time = strtotime("now");
    $addsalt = substr(md5($ip.uniqid($with_time,true)),0,15);
    $_SESSION['order_id'] = $addsalt;
}

 $order_id = $_SESSION['order_id'];

My cart.php (Session Logic Only)

 $user_sessid = $_SESSION['sessid'];
 $order_id = $_SESSION['order_id'];

 $userid = $_SESSION['user_id'];

 if(empty($userid)){

 $r_type = 1;   

 $q1=<<<SQL
select od.ipaddress, od.modified_ts, od.product_id,od.discount,od.quantity,p.id,p.name,p.price, p.img_dir,p.img_name from orders od, products p where od.order_id='$order_id' and od.user_sessid='$user_sessid' and od.product_id = p.id
 SQL;

} else {
$r_type = 2;

  $q1=<<<SQL
select uc.modified_ts, uc.product_id,uc.discount,uc.quantity,p.id,p.name,p.price, p.img_dir,p.img_name from user_cart uc, products p where uc.userid='$userid' and uc.product_id = p.id
  SQL;


}

 $r1=$db->query($q1);
 $num1 = $r1->num_rows;

When i'm echoing out the query on immediate reload of the cart page it is getting an empty order_id.

I'm wondering my head off as to how this weird thing is happening. Please help...

Update I am including a file on top of both the pages which has session_start on top of it and therefore it explains the user_sessid being created and used.

Upvotes: 1

Views: 1646

Answers (2)

codeaddict
codeaddict

Reputation: 879

You may need to add session_start() to the top of the file.

Edit: You said you were querying on the session id and order id, but you also have

and od.product_id = p.id 

at the end of your query. Where is this logic? I'm guessing that you are using a $_GET request or something similar to determine the product ID. Maybe this has something to do with your issue, possibly just remove it from the query? You should only need to use 1 unique key for your SQL query, especially as unique as the hash you're creating.

Upvotes: 1

dartacus
dartacus

Reputation: 644

An obvious point, but check you're definitely calling session_start() on both pages?

Upvotes: 0

Related Questions