无法在MYSQL中更新值序列化数组

时间:2012-01-19 11:35:39

标签: php mysql serialization

我在这里做什么

 - extract my serialize array from databse
 - deserialize it
 - change the value
 - after changing I serialize it
 - then write it back to MYSQL database table.

但我无法将其写回MYSQL数据库表

$myarray = Array
(
    [dogname] => Array
        (
            [0] => white
            [1] => zeon
            [2] => imao
        )

    [visit] => Array
        (
            [0] => once
            [1] => twice
            [2] => twice
        )
}

我用这种方式将数据库保存到我的表serialize($myarray)

现在我提取它并反序列化

$unserializearray = unserialize($myserialarray); 

then search for array value to change and back to table

$keys = array_keys($unserializearray['dogname'], 'imao', true);
foreach($keys as $key)
{
    // find dogname imao and change its visit to once
    $unserializearray['visit'][$key] = "once";


$update = serialize($unserializearray);

//save the update    
mysql_query("UPDATE dogdetails SET checkup = '$update'
WHERE dogid = '1'");
}

但它没有保存到mysql中我会错过代码吗?

2 个答案:

答案 0 :(得分:0)

首先,这不起作用,如果你的数组中有一个单引号,那么你需要做

$update=mysql_real_escap_string(serialize($unserializearray),$dbhandle);

或朋友。

更重要的是,你的数据库设计对我来说似乎有很大的缺陷:正如在这里说的那么多次,你不应该在一个字段中存储多个值,如果你想单独访问它们。在你的情况下,你用他们的vists存储三只狗,但是你想单独访问它们 - 这就是你的代码所做的。

答案 1 :(得分:0)

正如欧根所说,你的代码有很多问题。

除此之外,这段代码的效果是否更好:

$unserializearray = unserialize($myserialarray); 

then search for array value to change and back to table

$keys = array_keys($unserializearray['dogname'], 'imao', true);
foreach($keys as $key)
{
    // find dogname imao and change its visit to once
    $unserializearray['visit'][$key] = "once";
}

$update = mysql_real_escap_string(serialize($unserializearray));

//save the update    
mysql_query("UPDATE dogdetails SET checkup = '$update' WHERE dogid = '1'");