如何附加数据库中已经存在的序列化字符串 [英] How to append a serialized string that already exists in the database
问题描述
我刚刚开始学习序列化,但有一个问题似乎找不到简单的解释.
I have just started to learn about serialization and I have a question that I cannot seem to find a simple explanation to.
说我有一个名为week的表,一周之内有3列,第三列包含一堆序列化的餐ID,就像存储在我的数据库中一样:
Say I had a table called week and inside week I had 3 columns with the third column containing a bunch of serialized meal IDs like so stored in my database:
INSERT INTO `week` (`week_id`, `meal_code`, `meal_id`) VALUES
(1, 'week12016', 'a:6:{i:0;i:1;i:1;i:2;i:2;i:3;i:3;i:4;i:4;i:5;i:5;i:6;}');
但是后来我想在现有的字符串后附加另一个进餐ID,但不更新其他任何列,以便其读取
But later I want to append another meal_id to the existing string but not update any other column so it reads
(1, 'week12016','a:7:{i:0;i:1;i:1;i:2;i:2;i:3;i:3;i:4;i:4;i:5;i:5;i:6;i:6;i:7;}')
我已经尝试在php文件中存储以下内容
I have tried in a php file to store the following
$food=array("7");
$sfood=serialize($food);
然后尝试将7添加到周表中的现有进餐ID
Then trying to add the 7 to the existing meal_ids in the week table
mysqli_query($conn,"UPDATE week
SET meal_id ('$sfood')");
//if entry into the database is successful, confirm with a alert popup and refresh the home page
if(mysqli_affected_rows($conn) > 0){
//header("location: admin.php");
header("refresh:0; url=admin.php");
echo "<script type='text/javascript'>alert('Upload Successful!')</script>";
exit;
但是当我检查数据库时,什么都没有改变.
But when I check my database, nothing has changed.
我在做错什么,甚至有可能做我想达到的目标?
What am I doing wrong, is it even possible to do what I am trying to achieve?
推荐答案
您必须从表行中读取该列.将其反序列化为PHP变量,然后向其添加新的匹配项.
You have to read the column from your table row. Unserialize it into a PHP variable and then add a new occurance to it.
然后序列化新阵列并将其存储回数据库中
Then serialize the new array and store it back to your database
// SELECT from table
$s = 'a:7:{i:0;i:1;i:1;i:2;i:2;i:3;i:3;i:4;i:4;i:5;i:5;i:6;i:6;i:7;}';
$d = unserialize($s);
print_r($d);
$d[] = 99;
print_r($d);
$s2 = serialize($d);
echo $s2;
// UPDATE table row
结果
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
[6] => 7
)
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
[6] => 7
[7] => 99
)
a:8:{i:0;i:1;i:1;i:2;i:2;i:3;i:3;i:4;i:4;i:5;i:5;i:6;i:6;i:7;i:7;i:99;}
不建议这样存储数据,因为它使该数据无法使用查询进行处理
Storing data like this is not recommended, as it makes this data impossible to process using queries
这篇关于如何附加数据库中已经存在的序列化字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!