views:

395

answers:

4

Hi, I have another problem with my scripy now I have made it more advance, first off the count function doesnt work properly and it gives this error.

*Warning: array_push() [function.array-push]: First argument should be an array in C:\wamp\www\social\add.php on line 42*

Here is my script:

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

if (count($friends2) == 0) {

//option 1
$friends2 = array($id);
$friendsUpdated = serialize($friends2);
mysql_query("UPDATE users SET friends='$friendsUpdated' WHERE id='$myid'");

}else{

//option 2
array_push($friends2, $id);
$friendsUpdated = serialize($friends2);
mysql_query("UPDATE users SET friends='$friendsUpdated' WHERE id='$myid'");

Thnaks, Stanni

+1  A: 

It seems that $friends2 is not an array. Use the var_dump($friends2) function to see its value.

Gumbo
Hmm, it sats bool(false) that cant be right :s
Ryan
Then take a look into the manual, in what case unserialize returns false: http://docs.php.net/unserialize
Gumbo
A: 

This may not sound helpful, but your database design is quite stange.

Why is $friends2 not an array? Try to print_r () $friends after fetching an array to see if you actually get what you want from database in the first place.

Also, your count check is redundant. To add to an array, just go $friens2[] = $id; If $friends2 were empty, it will just make a new array of 1 element ($id), otherwise it will add it.

Ilya Birman
A: 

Your question contains the answer: unserialize($friends['friends']) seem to return non-array and count($friends2) is not zero - this can happen, for example, if number passed. Have you tried to examine the $friends['friends'] data? Simplest way would be to make additional check *is_array($friends2)*

Sergii
A: 

If you run this code right after having created the database but before putting any data in there, "unserialize($friends['friends']);" returns something other than an array. Probably an empty string. So in option 2, you may want to do something like this before array_push:

if (!is_array($friends2)) {
  $friends2 = array();
}

This way, if the person has no friends by this point (sad.. but you'll fix it by pushing a new friend to them), an empty friends list gets initialized.

Plus, any time you see two identical lines of code in different parts of the "if" condition...

$friendsUpdated = serialize($friends2);
mysql_query("UPDATE users SET friends='$friendsUpdated' WHERE id='$myid'");

That's a signal that you should restructure your code so that you'd only have one copy of these lines.

Jaanus
Thank-you to everyone who answered :) My code is now fully functioning :D
Ryan
Great to hear! You may also want to designate the answer that you like most, by clicking the big checkmark to the left.
Jaanus