php 从二维数组生成的单选按钮中获取表单提交数据

8e2ybdfx  于 2023-04-28  发布在  PHP
关注(0)|答案(2)|浏览(102)

我使用多维数组创建了一个包含单选字段的HTML表。
如何从表单提交中获取所选值?
当前代码:

$cakedata = array(
    array("shape" => "Heart",       "flavor" => "Chocolate",    "toppings" => "Cookies"),
    array("shape" => "Rectangle",   "flavor" =>  "Vanilla",     "toppings" =>  "Spun-sugar Flowers"),
    array("shape" => "Square",      "flavor" =>  "Lemon",       "toppings" => "Mini Chocolate Candies"),
    array("shape" => "Round",       "flavor" =>  "Cheesecake",  "toppings" => "Marshmallows")
);
echo "<form action = 'diycake.php' method = 'post'>";
echo "<table><table border = '1'>";
echo "<tr>";
    echo "<th> Cake Shape </th>";
    echo "<th> Cake Flavor </th>";
    echo "<th> Cake Toppings </th>";
$i = 0;
foreach($cakedata as $row => $innerArray){
    foreach($innerArray as $innerRow => $value){
        if($i==0){
            echo "<tr>";
        }
        echo "<td><input type ='radio' name ='radio".$i."'>".$value."</td>";
        if($i==2){  
            echo "</tr>"; 
            $i=-1;
        }
        $i++;
    }
}
echo "</tr>";
echo "</table><br>";
echo "<input type = 'submit' name = 'submit' value = 'Submit'>";
echo "</form>";
echo '<pre>'; print_r($cakedata); echo '</pre>';

如何接收用户的选择?

brgchamk

brgchamk1#

<html>
    <head>
        <title>DIY Cake</title>
    </head>
    <body>
        <h1>D-I-Y Cake</h1>
        <?php
        $cakedata = array(
                        array("shape" => "Heart",       "flavor" => "Chocolate",    "toppings" => "Cookies"),
                        array("shape" => "Rectangle",   "flavor" =>  "Vanilla",     "toppings" =>  "Spun-sugar Flowers"),
                        array("shape" => "Square",      "flavor" =>  "Lemon",       "toppings" => "Mini Chocolate Candies"),
                        array("shape" => "Round",       "flavor" =>  "Cheesecake",  "toppings" => "Marshmallows")
                );
        echo "<form action = 'diycake.php' method = 'post'>";
        echo "<table><table border = '1'>";
        echo "<tr>";
            echo "<th> Cake Shape </th>";
            echo "<th> Cake Flavor </th>";
            echo "<th> Cake Toppings </th>";
                $i = 0;
                foreach($cakedata as $row => $innerArray){
                    foreach($innerArray as $innerRow => $value){
                        if($i==0){
                            echo "<tr>";
                            }
                            echo "<td><input type ='radio' name ='radio".$i."' value='" . $value . "'>".$value."</td>";
                        if($i==2){  
                            echo "</tr>"; 
                            $i=-1;
                            }
                        $i++;
                    }
                }
        echo "</tr>";
        echo "</table><br>";
        echo "<input type = 'submit' name = 'submit' value = 'Submit'>";
        echo "</form>";

        ?>

    </body>
</html>

diycake.php

<?php

// check, if form was sent
if (isset($_POST['submit'])) {
  $outerNumberArray = 4; // actually the outer number of your array
  for($i = 0; $i < $outerNumberArray; $i++) {
    if (isset($_POST['radio' . $i])) {
      echo "Your value from radio" . $i . ": " . $_POST['radio' . $i] . PHP_EOL;
    }
  }
}
js81xvg6

js81xvg62#

单选按钮name属性在其相对组中应该是相同的。这样,取消选中同一“系列”中的其他单选按钮的行为可以自动化。您不应该将计数器附加到name值。
我建议用<label>标签 Package cake属性的单选按钮元素,这样文本就代表了一个可点击的元素,从而影响单选按钮。
作为一种最佳实践和提高代码可维护性的方法,通过引用$cakedata数组中的列和值来动态创建表的所有内容。如果您想在表格中添加或删除单元格,您只需要调整数组,而不需要调整HTML标记。Demo of printf()
如果您需要调整HTML标记,可以通过声明带有占位符的模板字符串来简化--这也是最佳实践,因为它可以减少更改。
如果您希望强制客户端验证每个单选按钮都有一个选择,请在每个组中的至少一个单选按钮上使用required。客户端验证永远不能替代服务器端验证;它只会改善用户体验。

  • [clearthrows]* 我必须警告,现代Web开发趋势表明,一些开发人员更喜欢使用客户端语言来填充HTML标记(而不是服务器端语言,如PHP)。

(下面的代码片段都没有实际测试。如果我犯了任何错误,请留下评论。)

$cakedata = [
    ["shape" => "Heart",     "flavor" => "Chocolate",  "toppings" => "Cookies"],
    ["shape" => "Rectangle", "flavor" => "Vanilla",    "toppings" => "Spun-sugar Flowers"],
    ["shape" => "Square",    "flavor" => "Lemon",      "toppings" => "Mini Chocolate Candies"],
    ["shape" => "Round",     "flavor" => "Cheesecake", "toppings" => "Marshmallows"]
];

$headings = array_keys($cakedata[0] ?? []);

$th = <<<TH
    <th>Cake %s</th>
TH;

$td = <<<'TD'
    <td><label><input type="radio" name="%1$s" value="%2$s" required>%2$s</label></td>
TD;

?>
<form action="diycake.php" method="post">
    <table border="1">
        <tr>
            <?php
            foreach ($headings as $name) {
                printf($th, htmlentities(ucwords($name)));
            }
            ?>
        </tr>
        <?php
        foreach ($cakedata as $row) {
            echo '<tr>';
                foreach ($row as $attr => $value) {
                    printf($td, htmlentities($attr), htmlentities($value));
                }
            echo '</tr>';
        }
        ?>
    </table>
    <input type="submit" name="submit" value="Submit">
</form>

提交表单时,$_POST有效负载将包含值为Submit$_POST['submit']。这应该是您在执行任何其他操作之前的第一次验证检查(如果表单提交没有通过所有验证,甚至不必连接到数据库)。
$_POST数组还将包含$_POST['shape']$_POST['flavor']$_POST['toppings']。您可以通过一次isset()调用轻松地检查它们是否存在,但也可以分别使用!empty()检查它们。因此,您还应该确认提交的值在$cakedata中也存在。如果您希望有一个稳定、安全的应用程序,这些繁重的验证是必不可少的。

if (isset($_POST['submit'])) {
    $valid = true;
    foreach (array_keys($cakedata[0] ?? []) as $column) {
        if (empty($_POST[$column]) || !in_array($_POST[$column], array_column($cakedata, $column))) {
            $valid = false;
            break;
        }
    }
    // only proceed with server-side processes if the submission was completely valid.
}

相关问题