Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can i insert a php array into a single mysql record field?

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?

like image 907
gianniskpf Avatar asked Feb 04 '26 13:02

gianniskpf


2 Answers

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.. */
    }
}
?>
like image 93
David Houde Avatar answered Feb 06 '26 02:02

David Houde


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)));
}
?>
like image 40
Jakub Avatar answered Feb 06 '26 02:02

Jakub