views:

621

answers:

4

Im trying to save serialized arrays into my mysql database then retrive them and unserilize them but I cant work out how to unserialize them. here is what I have so far:

$query = mysql_query("SELECT friends FROM users WHERE id='$myid'");
$friends = mysql_fetch_array($query);

unserialize($friends);

Stuck here ?????

array_push($friends, $id);
$friendsUpdated = serialize($friends);

mysql_query("UPDATE users SET friends='$friendsUpdated' WHERE id='$myid'");
+5  A: 

mysql_fetch_array returns an array, so you need to select the bit of the array you want:

$row = mysql_fetch_array($query);

$data=unserialize($row['friends']);

You should also get into the habit of checking for errors too, e.g.

$result = mysql_query("SELECT friends FROM users WHERE id='$myid'");
if ($result) 
{
    if ($row = mysql_fetch_array($result))
    {
         $data=unserialize($row['friends']);

    }
    else
    {
         //empty result, set up empty data?
         $data=array();
    }

} 
else 
{
    die('Invalid query: ' . mysql_error());
}
Paul Dixon
haha, thank-you sooo much :D
Ryan
A: 

Here's what you need to do:

$query = mysql_query("SELECT friends FROM users WHERE id='$myid'");
$friendsFromDatabase = mysql_fetch_array($query);
$friends = unserialize($friendsFromDatabase[0]);

I.e just grab the result from unserialize into a variable.

Jaanus
A: 

Since mysql_fetch_array() returns an array, you can't pass it directly to unserialize(). Instead of

unserialize($friends);

you need to use the first element in the array:

if (isset($friends[0])) {
  $friendsDataArray = unserialize($friends[0]);
} else {
  // not found.
}
Henrik Paul
+2  A: 
Energiequant