Page 1 of 1

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

Posted: 14 Dec 2014, 08:34
by Marius
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?

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

Posted: 14 Dec 2014, 09:10
by Admin
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