PHP函数serialize()与unserialize()

serialize — Generates a storable representation of a value,产生一个可存储的值的表示。

unserialize — Creates a PHP value from a stored representation,从已存储的表示中创建 PHP 的值。

serialize()就是将PHP中的变量如对象(object),数组(array)等等的值序列化为字符串后存储起来.序列化的字符串我们可以存储在其他地方如数据库、Session、Cookie等,序列化的操作并不会丢失这些值的类型和结构。这样这些变量的数据就可以在PHP页面、甚至是不同PHP程序间传递了。
而unserialize()就是把序列化的字符串转换回PHP的值。

//$newsID是一个通过_POST获到的数组
$Id=serialize($newsId);//将数组中的数据序列化直接存到数据库的字段中
$sql = "insert into article_specialtopic (banner,title,articleIDs)  values('$banner','$title','$Id')";
if (!mysqli_query($link,$sql))
{
    die('Error: ' . mysqli_error());
}else{
    echo 'success insert';
}
从数据库中取出数据反序列化存到数组中
$sql="select articleIDs from article_specialtopic where id=1";
$result=mysqli_query($link,$sql);
$value=$result->fetch_row();
//print_r($value[0]);
$string=(string)$value[0];
$data=unserialize($string);
print_r($data);

 

posted @ 2016-04-07 10:44  哈密瓜和柚子  阅读(249)  评论(0编辑  收藏  举报