Save Array in MySQL Database

You can store the array using serialize/unserialize. With that solution they cannot easily be used from other programming languages, so you may consider using json_encode/json_decode instead (which gives you a widely supported format). Avoid using implode/explode for this since you’ll probably end up with bugs or security flaws.

To convert an array (or any object) into a string using PHP, call the serialize():

$array = array( 1, 2, 3 );
$string = serialize( $array );
echo $string;

Now save $string value in your database.

$string will now hold a string version of the array. The output of the above code is as follows:

a:3:{i:0;i:1;i:1;i:2;i:2;i:3;}

Now read data from the database and convert back from the string to the array, use unserialize():

// $array will contain ( 1, 2, 3 )
$array = unserialize( $string );

For print array use this PHP code:

foreach ($array as $value) {
    echo $value."<br>";
}

Note that this makes your table non-normalized, which may be a bad idea since you cannot easily query the data. Therefore consider this carefully before going forward. May you need to query the data for statistics or otherwise? Are there other reasons to normalize the data?

Also, don’t save the raw $_POST array. Someone can easily make their own web form and post data to your site, thereby sending a really large form that takes up lots of space. Save those fields you want and make sure to validate the data before saving it (so you won’t get invalid values).

Leave a Comment