Good afternoon mates.
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 stores the data of said fields until I destroy it with the intention of being able to fill a table with the stored data in the same.
Can someone tell me how I should store the form data in a session array?
I am using Php. My code is the following but I get an error:
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 that I receive from the form and then display them in a table.
All the best.
The
Array String conversión
would occur in this line:because you are not referencing the indices that the array would have.
Doing this should solve the problem:
Another mistake you are making, this time in logic, is that you are getting too screwed up by thinking that you must tell the code in which position of the array the new data should be inserted . That's why you insist on checking if it's empty, on a counter
$i
and other stories. With this notation:$array[]=$elemento
, an element is inserted in the first or last position of the array depending on whether or not it is empty, I don't see why you have to first ask if it is empty or ask for its total number of elements and then increase it by one and insert there. All that is done just using the notation already mentioned. Also with your logic, in the first case, when you print this:It will print you
0
, when there is already an element.I'm going to greatly simplify your logic in the answer code: