簡體   English   中英

序列化/反序列化數據庫數據?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM