Store an Array in MySQL table column and use it in PHP

Discuss coding issues, and scripts related to PHP and MySQL.
Marius
Posts:107

Store an Array in MySQL table column and use it in PHP

Hi
I have an array in php:

Code: Select all

$arr = array(3, 'value 1', 'other value');
And a mysql table with these columns: id | name | data
I want to store /insert the $arr array in the "data" column, then to can select and use it in php.
How can I do this, how can I store a php array in mysql?

Admin Posts:805
Hi
You can store an array in a database into a string with JSON format.
Use json_encode() when you want to insert the array. For example:

Code: Select all

$arr = array(3, 'value 1', 'other value');
$sql = "INSERT INTO table (name, data)
VALUES ('The Name', '". json_encode($arr) ."')";
// ...   
- In the "data" column the $arr array will be stored into a JSON string like this:

Code: Select all

[3,"value 1","other value"]
- In the same way you can store eaven multi-dimensional array.
Then, when you select the data, use json_decode() to convert the JSON string back into an array in PHP.

Code: Select all

// Performs the Select ..
$arr = json_decode($row['data'], true);    // add true to convert into array