Storing an Array

I want to store an array within a mysql for future use. I was wondering what the best way of doing this is. I need to be able to retrieve it and be able to use it in its array form after retrieval.
Who is Participating?
hernst42Connect With a Mentor Commented:
use serialize and unserialze function of php. So you can even store objects in the database

Before the insert do a
$dbarr = serialize($array);

after you fetch the data from the database do a
$array = unserialize($row['array']);
If its a one dimensional array then the easiest way is like this (for example)

$array = array(1,2,3,4,5,6,7); //sample array
$db_string = implode("|",$array); //joins array in string like 1|2|3|4|5|6|7

$query = mysql_query("INSERT INTO tablename (fielname) VALUES ('$db_string')") or die(mysql_error());

Then after you pull the data out of the table (supposing the result was in $var)

$restored_array = explode("|",$var); //string from table is exploded back into an array
So the key parts are

implode -

to join the array together in a string to be inserted into the database


explode -

to break the string up into an array after you have pulled the string out of the database
ShroderAuthor Commented:
Unfortunetly it is a multi demensional array.  I just had to make things complicated :)
Boris AranovichSenior Software EngineerCommented:
yeah, serializing and unserializing should solve it. it keeps the format and the data exactly the same.
though, when you're inserting it to the DB, i think you should escape the string:
$dbarr = serialize($array);
$sql = "INSERT INTO table (fieldname) VALUES ('".mysql_escape_string($dbarr)."');";
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.