Use of array in session variable

1

Good afternoon, classmates.

I would like to save in a session variable the value of two fields that I pass through $ _post from a form and that this session variable will store the data of those fields until I destroy it with the intention of filling a table with the data stored in it.

Can someone tell me how to store the form data in a session array?

I am using Php. My code is the following but I have an error of:

  

Array String conversion.

$art = $_POST["select-productos"];
$und = $_POST["und-productos"];

$productos = array("articulo" => $art, "cantidad" => $und);

if (empty($_SESSION["listadecompra"])) {
    $i = 0;
    $_SESSION["listadecompra"][$i] = $productos;
} else {
    $i = count($_SESSION["listadecompra"]);
    $i++;
    $_SESSION["listadecompra"][$i] = $productos;
}

/* Creamos tabla de contenido */
$listado = $_SESSION["listadecompra"];

foreach ($listado as $value) {
   echo "<tr><td>" . $value . "</td><td>" . $value . "</td></tr>";
}

//var_dump($_SESSION["listadecompra"]);
echo "Total de productos: " . $i . "<br>";

What I intend is to be able to increase the array that I store in the session with the data I am receiving from the form and then display them in a table.

Greetings.

    
asked by jmrufo 13.12.2018 в 17:09
source

1 answer

0

The Array String conversión would occur on this line:

echo "<tr><td>" . $value . "</td><td>" . $value . "</td></tr>";

because you are not referring to the indexes that the array would have.

Doing this should solve the problem:

echo "<tr><td>" . $value["articulo"] . "</td><td>" . $value["cantidad"] . "</td></tr>";

Another error that you are committing, this time of logic, is that you are enroyando too when thinking that you must indicate to the code in which position of the array should insert the new data . That is why you insist on a verification of whether it is empty, in a $i counter and other stories. With this notation: $array[]=$elemento , an element is inserted in the first or last position of the array depending on whether it is empty or not, I do not see why you have to first ask if it is empty or ask for its total of elements for later increase in one and insert there. All this is done only using the aforementioned notation. Also with your logic, in the first case, when you print this:

echo "Total de productos: " . $i . "<br>";

It will print 0 , when there is already an element.

I will considerably simplify your logic in the response code:

$art = $_POST["select-productos"];
$und = $_POST["und-productos"];
$listado = $_SESSION["listadecompra"];

$productos = array("articulo" => $art, "cantidad" => $und);
$listado[] = $productos;

/* Creamos tabla de contenido */

foreach ($listado as $value) {
   echo "<tr><td>" . $value["articulo"] . "</td><td>" . $value["cantidad"] . "</td></tr>";
}


$allProducts = count( $listado);
echo "Total de productos: $allProducts<br>";
    
answered by 13.12.2018 / 18:54
source