序列化/反序列化数据库数据?

时间:2011-02-03 02:33:21

标签: php mysql

是否可以序列化表单发布的数据,并将其插入数据库,然后如果需要更新,则将其反序列化,只更新已更改的数据?

如果有可能,有人会提供/写一个小脚本来做这件事吗?

4 个答案:

答案 0 :(得分:2)

要直接回答您的问题,您需要做的就是:

$data = serialize($_POST);
$sql = "INSERT INTO `table` (`data`) VALUES ('".addslashes($data)."')";
...

但我强烈建议您不要序列化数据并将其放入数据库。它会使数据很难搜索,更新等。您将被迫依赖您的应用程序来维护数据的完整性!

我建议设计一个适合表单结构的数据库表...如果表单结构是动态的,那么你需要创建多个表来存储数据。

答案 1 :(得分:0)

是的,你可以这样做,但不清楚为什么你想要/需要。在数据库中查询序列化数据很困难/不可能,并且为了更新它,您必须从数据库中提取数据,对其进行反序列化,更新,序列化并更新相应的行。

答案 2 :(得分:0)

您可以使用JSON对POSTDATA进行编码并存储在数据库中。当您需要数据时,只需解码JSON。

答案 3 :(得分:0)

这是从序列化数据中提取单个字符串值的函数...

用法就像......

SELECT PARSE_PHP_SERIALIZED_DATA_STRING(
    `serialized_data`,  'EmailAddress'
)
FROM  `your_table` 
WHERE `serialized_data` LIKE  '%EmailAddress%'

这是功能:

DELIMITER $$
--
-- Functions
--
DROP FUNCTION IF EXISTS `PARSE_PHP_SERIALIZED_DATA_STRING`$$
CREATE FUNCTION `PARSE_PHP_SERIALIZED_DATA_STRING`(str_data BLOB, str_index VARCHAR(252)) RETURNS varchar(255)
    DETERMINISTIC
BEGIN
   -- Declare variables must be done at top of BEGIN END
   DECLARE start_pos INT;
   DECLARE string_out VARCHAR(255);
   DECLARE string_search VARCHAR(255);
   DECLARE quote_string VARCHAR(6);
   -- The indexes in a php serialized string are quoted and end with a semi-colon
   -- Setting the quote string incase the "developer" before you (who thought 
   -- it was  a good idea to dump serialized data in to a single column) then also 
   -- randomly html encoded the string every third row.
   SET quote_string = '"';
   SET string_search = CONCAT(quote_string, str_index, quote_string, ';');
   -- search for the index
   SET start_pos = LOCATE(string_search, str_data);
   IF start_pos = 0 THEN
     -- not found it so lets search again but with html entities
     SET quote_string = '"';
     SET string_search = CONCAT(quote_string, str_index, quote_string, ';');
     SET start_pos = LOCATE(string_search, str_data);
   END IF;
   -- still not found it, then it is not there as an index
   IF start_pos = 0 THEN RETURN ''; 
   END IF;
   -- cut up the string to get just the value
   -- the offsets here work for string values
   -- maybe a different function for integer values??
   SET start_pos = start_pos + LENGTH(string_search);
   SET string_out = SUBSTRING(str_data, start_pos,255);
   IF SUBSTRING(string_out,1,2) = 'N;' THEN
     RETURN '';
   END IF;
   SET string_out = SUBSTRING(string_out, LOCATE(quote_string,string_out)+LENGTH(quote_string), LOCATE(quote_string,string_out,LOCATE(quote_string,string_out)+1));
   SET string_out = SUBSTRING(string_out, 1,LOCATE(quote_string,string_out)-1);
   RETURN string_out;
   END$$

DELIMITER ;