简体   繁体   English

带有复选框的HTML表单和使用PHP提交的数字类型?

[英]HTML form with checkbox and number types submission with PHP?

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. 它们从$id_producto获得值,在输入数字类型的情况下,我将"Number"连接起来,因此它们不会获得相同的名称。

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? 在该循环内执行另一个$ _POST ['somevariable']可以吗?
How can I concatenate that argument inside the square brackets? 如何在方括号内连接该参数?

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];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM