Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save array in mysql database

Tags:

arrays

php

mysql

I want to save extra information before sending the total order to Paypal. For each item I have created a single column in my MySQL database where I want to store it. Now I was thinking to save it as an array which I can read later for creating a PHP page. Extra fields are taken from input form fields.

By using an array can I be sure not to mixup information?

like image 719
user1343454 Avatar asked May 21 '12 13:05

user1343454


People also ask

How do I save an array in MySQL?

Use the PHP function serialize() to convert arrays to strings. These strings can easily be stored in MySQL database. Using unserialize() they can be converted to arrays again if needed.

Can I store array in database?

An array is a special variable that allows storing one or more values in a single variable e.g. – holding usernames or details in an Array. They are easier to manipulate. Sometimes, require to store Array in the MySQL database and retrieve it.

How do I create an array query in MySQL?

By using MYSQL_BOTH (default), you'll get an array with both associative and number indices. Your example shows it best, you get the same value 18 and you can access it via $v[0] or $v['type'] . Show activity on this post.


2 Answers

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.

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 which 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).

like image 61
Emil Vikström Avatar answered Sep 18 '22 23:09

Emil Vikström


The way things like that are done is with serializing the array, which means "making a string out of it". To better understand this, have a look on this:

$array = array("my", "litte", "array", 2);  $serialized_array = serialize($array);  $unserialized_array = unserialize($serialized_array);   var_dump($serialized_array); // gives back a string, perfectly for db saving! var_dump($unserialized_array); // gives back the array again 
like image 23
Sliq Avatar answered Sep 18 '22 23:09

Sliq