suppose we have a mysql table "table" with fields "user" "siblings" and we want to store this family info for every user.
is it possible to do this:
$user=35;
$sibs=array("george","christina");
mysql_query("insert into table (user,siblings) values ('$user','$sibs')");
so that field "siblings" contains an array?
You want to use PHP's serialize() function for this. To reverse the process, use unserialize()
Snippit from PHP.net:
<?php
// $session_data contains a multi-dimensional array with session
// information for the current user. We use serialize() to store
// it in a database at the end of the request.
$conn = odbc_connect("webdb", "php", "chicken");
$stmt = odbc_prepare($conn,
"UPDATE sessions SET data = ? WHERE id = ?");
$sqldata = array (serialize($session_data), $_SERVER['PHP_AUTH_USER']);
if (!odbc_execute($stmt, $sqldata)) {
$stmt = odbc_prepare($conn,
"INSERT INTO sessions (id, data) VALUES(?, ?)");
if (!odbc_execute($stmt, $sqldata)) {
/* Something went wrong.. */
}
}
?>
To build on @David Houde's answer from the post he refered to also use compression to save space (if useful to you):
<?php
mySerialize( $obj ) {
return base64_encode(gzcompress(serialize($obj)));
}
myUnserialize( $txt ) {
return unserialize(gzuncompress(base64_decode($txt)));
}
?>
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