Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store a PHP array in a single SQL cell

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

like image 356
Hector James Haddow Avatar asked Jul 20 '12 08:07

Hector James Haddow


1 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.

  • http://php.net/manual/en/function.serialize.php
like image 63
Eric Herlitz Avatar answered Oct 15 '22 09:10

Eric Herlitz