I use php serialize() to serialize an array. Then I put it in the database (column type text). My array contains other language character like chinese or japanese characters.
It is able to serialize and store it in database correctly however, when I obtain the serialized array out of database and unserialize it so I can use the array, it won't work, the unserialize array will just be blank.
here's my code, Save script:
$all = array (
"points" => '123',
"photo" => '写真',
"video" => 'video'
);
$sall = serialize($all);
mysql_query("UPDATE users SET lang = '$sall' WHERE uname='$uname'")
or die(mysql_error());
Retrieve script:
$result = mysql_query("SELECT * FROM users WHERE uname='$uname'")
or die(mysql_error());
$row = mysql_fetch_array($result);
if($row) {
$lang = $row['lang'];
$orilang = unserialize($lang);
// orilang contains the array
echo $orilang['photo'];
}
else {
}
$orilang['photo'] came out empty but $lang has the serialized data.
As serialize() is not binary safe I'd suggest you to use json to encode you data:
$all = array (
"points" => '123',
"photo" => '写真',
"video" => 'video'
);
$sall = json_encode($all);
// {"points":"123","photo":"\u5199\u771f","video":"video"}
$decode = json_decode($sall, true);
/*array(3) {
["points"]=>
string(3) "123"
["photo"]=>
string(6) "写真"
["video"]=>
string(5) "video"
}*/
As a side note, if you started building something I'd suggest you move to MySQLi or PDO, mysql_* functions are deprecated. Here is a nice tutorial to get you started on PDO.
To get results:
$result = mysql_query("SELECT * FROM users WHERE uname='$uname'")
or die(mysql_error());
$row = mysql_fetch_assoc($result);
if($row) {
$lang = $row['lang'];
$orilang = json_decode($lang, true);
// orilang contains the array
echo $orilang['photo'];
// or
// $orilang = json_decode($lang);
// echo $orilang->photo;
} else {
}
You can try json instead
$all = array (
"points" => '123',
"photo" => '写真',
"video" => 'video'
);
$sall = json_encode($all);
mysql_query("UPDATE users SET lang = '$sall' WHERE uname='$uname'")
or die(mysql_error());
$result = mysql_query("SELECT * FROM users WHERE uname='$uname'")
or die(mysql_error());
$row = mysql_fetch_array($result);
if($row)
{
$lang = $row['lang'];
$orilang = json_decode($lang,true);//for getting assoc array add second param as true
//orilang contains the array
echo $orilang['photo'];
}
else{
}
Refer http://php.net/manual/en/function.json-decode.php
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With