Peter Stuart
Peter Stuart

Reputation: 2434

Adding variables to $_SESSION

I have got a basic login script at the moment.

When the user logs in 2 variables are defined:

$_SESSION['user_id'] = $user['user_id'];
$_SESSION['username'] = $user['username'];

the index.php file has this

session_start();
if(array_key_exists('user_id', $_SESSION) && array_key_exists('username', $_SESSION)):

That is all fine, however once the session is started I would like to add more values from a database so I have this code here:

$res = mysql_query($sql);
$_SESSION = mysql_fetch_assoc($res);

When I do this it overrides the $_SESSION['user_id'] and $_SESSION['username']. I tried this:

$_SESSION .= mysql_fetch_assoc($res);

but it didn't work.

Does anyone have any ideas?

Thanks peter

Upvotes: 1

Views: 380

Answers (4)

Gecko
Gecko

Reputation: 74

Functions mysql_* are deprecated and removed in the future, use PDO or MySQLi is recommended.

Some hosters have disabled these functions.

Upvotes: 1

useful
useful

Reputation: 472

Try merging the arrays

$res = mysql_query($sql);
$_SESSION = array_merge(mysql_fetch_assoc($res), $_SESSION);

See http://php.net/manual/en/function.array-merge.php

Upvotes: 1

Björn Kaiser
Björn Kaiser

Reputation: 9912

That's because you're setting the value of the variable $_SESSION to the return value of mysql_fetch_assoc($res);.

What you want to do is something like $_SESSION['query_result'] = mysql_fetch_assoc($res). If you just want to add a single column of your database result to the session you would do it like this:

$res = mysql_query($sql);
$data = mysql_fetch_assoc($res);
$_SESSION['myKey'] = $data['myKey'];

Upvotes: 5

Galen
Galen

Reputation: 30170

$_SESSION is an array. You are over-riding the entire $_SESSION variable. Do this instead:

$_SESSION['data'] = mysql_fetch_assoc($res);

https://www.php.net/manual/en/session.examples.basic.php

Upvotes: 6

Related Questions