...

View Full Version : PHP's serialize function not working!!



noisyscanner
03-12-2010, 12:41 PM
Hello all!
I have a script that SHOULD add friends to a users account by:
Checking the db to see if he has any friends.
If he doesn't, initialize an array with the friend he wants to add:
array($friend);
If he has friends already, unserialize his friends array
$friends = unserialize($row['friends']) and ARRAY_PUSH() the new friend on the end then serialize it:

serialize(array_push($friends,$friend))
Then insert it into my DB.
What I don't get is the fact that in my db one time i get "a:1:{i:0;s:9:"some_user";}" next time i get "i:2;" then if I add another friend i get "b:0;"
HERE IS MY SCRIPT:

<?php
session_start();

if($_GET[cmd] == "friend"){

mysql_connect("localhost", "user", "pass") or die(mysql_error());
mysql_select_db("user_db") or die(mysql_error());

$friend = $_GET['friend'];

$find_friends = mysql_query("SELECT * FROM tablename WHERE user='$_SESSION[username]'");

while ($row = mysql_fetch_array( $find_friends )) {
if($row['friends'] == "")
{
$new_friend_array = array($friend);
}
else
{
$new_friend_array = array_push(unserialize($row['friends']),$friend);
}

print_r(unserialize($row['friends']));
print_r(array_push(unserialize($row['friends']),$friend));
}
$new_friend_array_serial = serialize($new_friend_array);
echo $new_friend_array_serial;
print_r(unserialize($new_friend_array_serial));
mysql_query ("UPDATE tablename SET friends='$new_friend_array_serial' WHERE user='$_SESSION[username]'") or die (mysql_error());
header("Location: ../user/$_SESSION[username]&msg=$friend is now your friend!");
}
?>
This seems strange.. very strange. Hopefully somebody knows the answer to this question!!
My php version is: 5.2.8
Thanks,
Noisyscanner:o:):confused::(:thumbsup::eek::cool::rolleyes::mad::p

skywalker2208
03-12-2010, 02:10 PM
So what exactly is the problem with the serialized string? If you unserialize the sting do you get the expected result?

Fou-Lu
03-12-2010, 03:19 PM
You're use of array_push is not correct. Array_push returns an integer result indicating the total number of items in the array. Attempting to serialize this will result in a serialized string of the datatype and count: {i:2} for example.
Correct this by splitting the array_push and serialize into two separate calls.

noisyscanner
03-12-2010, 09:54 PM
Correct this by splitting the array_push and serialize into two separate calls.
Great so how would i do that?

kbluhm
03-12-2010, 10:11 PM
Great so how would i do that?

Push the value into the array.

Then serialize it.

skywalker2208
03-13-2010, 02:20 AM
Great so how would i do that?

Look at the example here (http://us2.php.net/array_push).

noisyscanner
03-14-2010, 08:40 PM
Thanks!!!!



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum