Help please, the problem is as follows. I get a string from the json database containing the user id, convert it to an array using json_decode (), delete the id’s name and convert the array back to the json string and when I try to access this string (I get the following error 'Fatal error: Uncaught Error: Cannot use object of type stdClass as array '), but if I delete the last element of the array, then everything is fine. What can be wrong?
public static function DeleteEventByUser($user_id, $news_id) { $user_id = intval($user_id); $news_id = intval($news_id); $link = db::getConnection(); $result = $link->prepare("SELECT `events` FROM `user` WHERE `id` = :user_id"); $result->execute(array('user_id' => $user_id)); $string = $result->fetch(); $record = $string['events']; $massive = json_decode($record); if (is_array($massive) and !empty($massive)) { foreach ($massive as $key => $value) { if ($value == $news_id) { unset($massive[$key]); } } $record = json_encode($massive); $result = $link->prepare("UPDATE `user` SET `events` = :record WHERE `id` = :user_id"); $result->execute(array('record' => $record, 'user_id' => $user_id)); return true; } return false; } Error occurs when executing this script.
public static function addEvent($user_id,$news_id) { $user_id = intval($user_id); $news_id = intval($news_id); $link = db::getConnection(); $result = $link->prepare("SELECT `events` FROM `user` WHERE `id` = :user_id"); $result->execute(array('user_id' => $user_id)); $record = $result->fetch(); $record = $record['events']; if (is_string($record)) { $list = array(); $list = json_decode($record); $list[] = $news_id; $record = json_encode($list); } else { $list = array(); $list[] = $news_id; $record = json_encode($list); } $result = $link->prepare("UPDATE `user` SET `events` = :record WHERE `id` = :user_id"); $result->execute(array('record' => $record, 'user_id' => $user_id)); }