Home » Php » mysql – Store a PHP array in a single SQL cell

mysql – Store a PHP array in a single SQL cell

Posted by: admin July 12, 2020 Leave a comment

Questions:

I wish to store the ingredients if an item as an array or similar data type in my SQL Database and cannot able to find satisfactory information on the subject

In PHP, the information will get stored as ingredient["$id"]=true or false, where $id represents an ingredient

So for plain bread (please note this is mostly still pseudo code as the data entry side has not yet been started)

//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

‘PLAIN BREAD: WHEAT FLOUR, WATER, SALT, YEAST.’

I looked in to ENUM and SET but that would make adding new ingredients harder

How to&Answers:

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

$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 reverse use unserialize

$unserializedString = unserialize($str);

You can use this for both arrays and objects.

Answer:

I wish to store the ingredients if an item as an array or similar data type in my SQL db an cannot find satisfactory information on the subject

If serialising data is the answer to a database-oriented question, chances are that you’re asking the wrong question. Normalise your database, and you’ll probably insert the ingredients into a separate table, using a JOIN to retrieve them. This makes your database easier to use, more searchable and more maintainable.

That said; there are cases where storing a serialised string is actually the most viable solution, but this one doesn’t seem to be that case.