Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update serialize data in MySQL

I have this serialize data in my mySQL database

a:4:{i:0;s:7:"bvl.png";i:1;s:8:"ccop.jpg";i:2;s:11:"reyborn.png";i:3;s:13:"swopgroup.jpg";}

How can I update this data, for example I want to delete ccop.jpg?

like image 210
Rey Calantaol Avatar asked Apr 10 '11 15:04

Rey Calantaol


3 Answers

Do not store serialized data in database.

Create a linked table consists of main_id and picture and store your image names in it.
So, you will have distinct access to them.

like image 61
Your Common Sense Avatar answered Oct 21 '22 02:10

Your Common Sense


You have to fetch the value from the database, unserialize it, remove the element, serialize it and save again.

$remove = "ccop.jpg";

//
// get the string from the database
//

$arr = unserialize($str);

foreach($arr as $key => $value)
  if ($value == $remove) unset($arr[$key]);

$str = serialize($arr);

//
// save the string back to the database
//

Instead of saving serialized list of values, it's better to have a normalized database and just do a simple DELETE FROM images WHERE object_id = ....

like image 20
Czechnology Avatar answered Oct 21 '22 02:10

Czechnology


Ideally you need to

  • extract it
  • deserialize it
  • modify it
  • serialize it
  • write it back to the database.
like image 3
David Gillen Avatar answered Oct 21 '22 03:10

David Gillen