1

My site has a list of users and each user is a member of different areas (groups, locations, etc). Instead of making a DB call every time I want to make a list, I want to store the array variables in session.

    //creates the array of groups that the user is in
    $_SESSION['gx']=mysql_query("SELECT * FROM `members` WHERE `user`='$user'");

Now my page loads and session_start() runs. However, when my page goes to retrieve that session variable, it's not there. Any suggestions?

Thanks

1
  • 1
    mysql_query does not return an array ... it returns a result resource ... you'll need to build the array from the query result ... Commented Mar 16, 2012 at 17:08

5 Answers 5

4

The return value of mysql_query cannot be serialized (stored into a session). But you can pull the results out a regular array and serialize that:

$res = mysql_query("SELECT * FROM `members` WHERE `user`='$user'");
if ($res) {
    $_SESSION['gx'] = mysql_fetch_array($res);
}

Warning: Depending on where $user gets its value from, this code might be vulnerable to SQL injection. Code responsibly.

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

Comments

1

mysql_query() doesn't return an array of the results, it returns a resource which you can use for mysql_fetch_array(), etc.

You have to fetch the data first:

$res = mysql_query("SELECT * FROM `members` WHERE `user`='$user'") or die('Error!');

$_SESSION['gx'] = array();
while ( $arr = mysql_fetch_array($res, MYSQL_ASSOC) )
{
  $_SESSION['gx'][] = $arr;
}

I believe that the usernames are unique, so you only need one call to mysql_fetch_*(), for example:

$res = mysql_query("SELECT * FROM `members` WHERE `user`='$user'") or die('Error!');

$_SESSION['gx'] = mysql_fetch_array($res, MYSQL_ASSOC);

Comments

0

mysql_query() does not return an array, but a resource. Get the values out of the resource first and then store the result in your session.

Comments

0

You are executing a query but are returning a resource, not results. You need to fetch an array if you want the data.

$_SESSION['gx']=mysql_fetch_array(mysql_query("SELECT * FROM `members` WHERE `user`='$user'"));

Comments

0

mysql_query() returns a ressource, you need to fetch this ressource in an array like this:

$query = mysql_query("SELECT * FROM `members` WHERE `user`='" . mysql_escape_string($user) . "'");
$_SESSION['gx'] = mysql_fetch_array($query, MYSQL_ASSOC);

Also, you have a potential security hole. You probably want to escape $user with mysql_escape_string() to avoid SQL injections.

1 Comment

That was it - thanks a lot. "$user" comes from a variable that was escaped when it was posted from the login page, so it's clean - thanks for the warning anyway.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.