Link to home
Start Free TrialLog in
Avatar of Crazy Horse
Crazy HorseFlag for South Africa

asked on

Is it okay to create multiple session variables with user data upon login

I had this question after viewing simple shopping cart database structure.

I want to store the users details in the summary table as per the above question. I just wanted to know if it would be okay to store the users personal data in session variables when they login i.e.: email address, shipping/billing address, and so on... All the values for the sessions would be set when the user logs in.
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

You might be talking about the "active record" design pattern.  Sure, it's OK to store this information in the session.  It might make better sense to store all of the user's personal data in a "user" array or object, and then store that thing in the session.  This would help keep the number of session variables to a minimum.
Avatar of Crazy Horse

ASKER

Thanks Ray,

I am not 100% sure on how to do that. Would it be something like this?


//run a SELECT query to get user details from database and declare variables (sanitize is a helper function)
$user_email = sanitize($row['user_email'];
$address1 = sanitize($row['address1'];
// some more defined here

$_SESSION['user_array'] = array("user_id" => $user_id,  "user_email" => $user_email, "address1" => $address1));

Open in new window


Then when I wanted to access them I could use a foreach loop?
ASKER CERTIFIED SOLUTION
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
This is so cool!  Where has it been all my life?? I wonder if I can use this most times instead of what I am doing now which is:

$row = $result->fetch_assoc();

Open in new window


Seriously, this is awesome.

I am using prepared statements and tried this:

$stmt = $link->prepare("SELECT * FROM `users` WHERE `user_id` = ? LIMIT 1");
$stmt->bind_param("i", $_SESSION['customer_id']);
$stmt->execute();
$result = $stmt->get_result();
if($result) {
	$obj = $result->fetch_object();
	echo $obj->first_name . " " . $obj->last_name;
	
}

Open in new window


Seems to work okay...
Oh, can I still use my sanitize function like this?

echo sanitize($_SESSION['user_details']->address1)

Open in new window

I don't know your sanitize() function, so I really can't comment without seeing it.  What you should be doing in the View layer is preparing the variables for browser output using htmlentities().
My sanitize function does just that :)

function sanitize($dirty) {
	return htmlentities($dirty, ENT_QUOTES, "UTF-8");
}

Open in new window

OK, great.  Don't use that when you pull information out of the database.  Use it, as the last things you do, before you put information into your site templates or browser output.