Reputation: 8376
For learning purposes, I'm doing this website where user can select some items and the number of units he wants, let's say it's this simplest shopping app.
So, I read from database the existing items in catalog:
$queryResult=$mySQL->query("SELECT nombre, precio, id FROM productos");
Then I print the list of products:
$queryResult=$mySQL->query("SELECT nombre, precio, id_producto FROM productos");
echo "<form action=\"checkout.php\" method=\"POST\">";
while($datos=$mySQL->fetch_array($queryResult))
{
$nombre=$datos['nombre'];
$id_producto=$datos['id_producto'];
$precio=$datos['precio'];
echo "<h1>$nombre</h1>";
echo "<input type=\"checkbox\" name=\"$id_producto\" value=\"on\"> Cantidad: <input type=\"number\" name=\"$id_producto"."Number\""." min=\"1\" max=\"20\" step=\"1\" value=\"1\"><br>";
echo "<h3>Precio: $precio</h3><br>";
}
echo "<br>";
echo "<input type=\"submit\" class=\"button\" value=\"Comprar\">";
echo "</form>";
They get as value the ones from $id_producto
, in the case of the number type inputs I concatenate "Number"
so they dont get the same name.
After submission, I'm trying to do something like:
foreach($_POST as $post_key => $post_value){
if ($post_value=="on") {
$var1 = $_POST['.$post_key."Number".'];
}
}
So if a checkbox was selected I check for its corresponding numeric value.
Is it OK to perform another $_POST['somevariable'] inside that loop?
How can I concatenate that argument inside the square brackets?
Upvotes: 0
Views: 111
Reputation: 780787
You don't need the single quotes, that's for when the key is a constant string. Since your key is an expression, just put that expression inside the brackets:
if ($post_value=="on") {
$var1 = $_POST[$post_key."Number"];
}
A better way to do this is to post the inputs as arrays:
echo "<input type=\"checkbox\" name=\"producto[]\" value=\"$id_producto\"> Cantidad: <input type=\"number\" name=\"Number[$id_producto]\" min=\"1\" max=\"20\" step=\"1\" value=\"1\"><br>";
Then you can use the loop:
foreach ($_POST['producto'] as $post_value) {
$var1 = $_POST['Number'][$post_value];
}
Upvotes: 1