[英]Serialize/Unserialize database data?
是否可以序列化表单发布的数据,然后将其插入数据库,然后如果需要更新,请对其进行反序列化,然后仅更新已更改的数据?
如果有可能,有人会友好地提供/编写一个小脚本来执行此操作吗?
要直接回答您的问题,您需要做的就是:
$data = serialize($_POST);
$sql = "INSERT INTO `table` (`data`) VALUES ('".addslashes($data)."')";
...
但是,我强烈建议您不要序列化数据并将其放入数据库。 这将使数据非常难以搜索,更新等。您将不得不依靠应用程序来维护数据的完整性!
我建议您设计一个适合您表格结构的数据库表...如果您的表格结构是动态的,那么您将需要创建多个表来存储数据。
这是从序列化数据中提取单个字符串值的函数...
用法就像...
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 ;
是的,你可以做到这一点,但不清楚为什么你会想要/需要。 一旦序列化的数据进入数据库中,就很难/不可能进行查询,并且要对其进行更新,您将不得不从数据库中提取数据,反序列化,更新,序列化并更新适当的行。
您可以使用JSON对POSTDATA进行编码并存储在数据库中。 当您需要数据时,只需解码JSON即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.