3

I am have created a 'liking' system for a site but I'm having a bit of trouble with json_encode and json_decode. I use arrays to store who has liked a post, so I need these 2 functions to make it storable, but for some reason it sometimes saves an object to the database:

{"1":"admin"}

instead of an Array (which I want):

["admin"]

This is my code:

if ($liked_by == NULL){ $liked_by = Array(); }
if (! in_array($user, $liked_by)){
  $liked_by[] = $user;
  $likes = $row['likes']+1;
  $liked_by = json_encode($liked_by);
  mysql_query("UPDATE $stream SET liked_by = '$liked_by' WHERE id = ".$id, $db)
    or die(mysql_error($db));
  mysql_query("UPDATE $stream SET likes = '$likes' WHERE id = ".$id, $db)
    or die(mysql_error($db));
} else{
  if(($liker = array_search($user, $liked_by)) !== false) {
    unset($liked_by[$liker]);
  }
  $likes = $row['likes']-1;
  $liked_by = json_encode($liked_by);
  mysql_query("UPDATE $stream SET liked_by = '$liked_by' WHERE id = ".$id, $db)
    or die(mysql_error($db));
  mysql_query("UPDATE $stream SET likes = '$likes' WHERE id = ".$id, $db)
    or die(mysql_error($db));
}

Sorry about using deprecated mysql functions...

I'm just not sure what's happening. Thanks in advance.

  • 2
    thats fine since you can get it back as `json_decode($data,true)` as an array – Abhik Chakraborty Apr 05 '14 at 08:05
  • The zero index seems missing in your example, which could cause the problem, the reason may be your `unset()` call. A simple solution would be to call [`array_values()`](http://www.php.net/manual/en/function.array-values.php) right before encoding. – Sirko Apr 05 '14 at 08:06
  • ^ see [`json_dencode()`](http://www.php.net/manual/en/function.json-decode.php)'s documentation. – Sam Apr 05 '14 at 08:06
  • This doesn't happen all the time, it just seems to happen at random moments. –  Apr 05 '14 at 08:07
  • @Sirko how do you mean? –  Apr 05 '14 at 08:10
  • `$liked_by = json_encode($liked_by);` => `$liked_by = json_encode( array_values($liked_by) );`. It's kind of a dirty workaround, though. – Sirko Apr 05 '14 at 08:11
  • why did you not have normalized your database ? Also, in an update statement, you can change multiple columns in one row in one query. Fe `("UPDATE $stream SET liked_by = '$liked_by', likes = '$likes' WHERE id = ".$id, $db)`. Also there is no excuses for using deprecated functions. Sorry – KarelG Apr 05 '14 at 08:13
  • If you think your solution would work you could post it as an answer. –  Apr 05 '14 at 08:33
  • @Abhik Chakraborty That works great! Can you post it as an answer? –  Apr 05 '14 at 09:52

1 Answers1

0

You can use as

json_decode($data,true);

where $data is the saved data from DB.

The above will return an array and you can manipulate it for further operation.

Abhik Chakraborty
  • 44,654
  • 6
  • 52
  • 63