Inserting into a serialized array in PHP
This is my first time here and I have been pulling my hair out over this one, so I thought it would be a good first question for me.
I am saving some array data to a mysql database, 开发者_开发技巧and then later I am using unserialize to edit it. The problem is that it blanks out every other index in the array when I edit just one index. Here is some example code:
foreach($post as $key => $value) {
if (isset($row)) {
if ($i > 2) { $tempArray = unserialize($row[$i]); }
}
$tempArray[$time] = $value;
if ($key == 'pid' || $key == 'uid') { $data[$key] = $value; }
else { $data[$key] = serialize($tempArray); }
$i += 1;
unset($tempArray);
}
Thanks for any insight you can give.
to store serialized array data in mysql and to retrieve and save it back to the same table, here is how you have to do it.
Fetch the serialized data from the table and unserialize it and store the array data inside a variable. make changes to the array data by using the variable we stored the data.
Again we serialize the variable having the modified array and update the mysql table field with the new serialized data.
For example:
$data = array(
"uid" => "some value",
"pid" => "some value"
);
$store_in_database = serialize($data);
/* ...do the mysql insert query to store the new data in the field (serializedfield)... */
Now to update the serialize data stored in the database table field.
/* ... fetch the row of the table or records any way you like (single record or multiple) */
foreach($db_result as $db_row){
$temp_array = $db_row['serializedfield'];
$temp_array['uid'] = "a new value";
$temp_array['pid'] = "another new value";
/* ... i wanted to add another array value */
$temp_array['akey'] = "some value";
$store_database = serialize($temp_array);
/* ... do the mysql update query to replace this new data with the old one. */
unset($temp_array);
}
The above is just to give you an idea. I hope you have understood how it should be done here.
精彩评论