Store PHP array in single SQL cell

I want to store the ingredients if the element as an array or similar data type in my SQL database, and can not find satisfactory information on this

In PHP, information will be stored as ingredient["$id"]=true or false , where $ id is a component

So, for plain bread (note that this is basically a pseudo code, since the data entry side is not running yet)

 //code that creates array this bit is still theory and will be manually emulated in the db for the time being $id=1; while (isset ($_POST["ingredient part of form".$ID])){ if ($_POST["ingredient".$id]==checked){ $p["ingredient"][$id]=true; } else{ $p["ingredient"][$id]=false } $id++; } //the code that gets the values back for the ingredient name we will use a separate array ingredient_n[$id] echo p[$prod_id]["item"].': ' $id=1 while (isset ($ingredient[$id])){ if ($p[$prod_id]["ingredient"][$id]==true) if ($id!=1){ echo ', '; } echo $ingredient_n[$id]; } } echo '.'; 

This should produce something like

"PLASMA BREAD: WHEAT, WATER, SALT, YEAR."

I looked at ENUM and SET, but that would make it harder to add new ingredients

+7
source share
2 answers

Judging by the topic (Store a PHP array in a single SQL cell), you should serialize this. There are standardized methods for this.

 $array["a"] = "Hello"; $array["b"] = "World"; $array["c"] = "!"; $str = serialize($array); // The contents of $str // a:3:{s:1:"a";s:5:"Hello";s:1:"b";s:5:"World";s:1:"c";s:1:"!";} 

To cancel using unserialize

 $unserializedString = unserialize($str); 

You can use this for both arrays and objects.

+13
source

I want to store the ingredients if the element as an array or a similar data type in my SQL db a cannot find satisfactory information on this

If data serialization is the answer to a database-oriented question, most likely you are asking the wrong question. Normalize your database, and you will probably enter the ingredients in a separate table using JOIN to retrieve them. This makes your database easier to use, more searchable, and easier to maintain.

That said; There are times when storing a serialized string is actually the most viable solution, but it doesn't seem to be.

+4
source

All Articles