1

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

2
  • I would like to add that this is a bad idea. You should only store the user ID in the session as the username, role, email, etc.. might change at some point. It's better to load what is needed on each page. Commented Nov 28, 2011 at 18:53
  • If I do that then the site will be slower as it is loading loads of data each time. The data on this database won't change unless the user changes it, when the user changes his account info the $_SESSION variables will be re-defined Commented Nov 29, 2011 at 12:46

4 Answers 4

6

$_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

Sign up to request clarification or add additional context in comments.

Comments

5

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'];

Comments

1

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

1 Comment

Switch the order of array merge's parameters to avoid overwriting previous values in $_SESSION.
1

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

Some hosters have disabled these functions.

1 Comment

This was asked 2 years ago :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.