简体   繁体   English

如何循环遍历表单中的输入数组?

[英]How to loop through an array of inputs in a form?

I am trying to look through some input fields in a form and add them to a database.我正在尝试查看表单中的一些输入字段并将它们添加到数据库中。 The user sets the number of fields, so I can't do something like the code below because there is no specific number of fields.用户设置了字段数,所以我不能像下面的代码那样做,因为没有特定的字段数。

for($i=0; $i<(number-of-fields); $i++)
{
    $_REQUEST['Question+$i']
}

I have tried this as well:我也试过这个:

<?php
$con=mysqli_connect("","test","test","Flashcards");

foreach($_REQUEST['Question[]'] as $value)
    {
    $newcards="INSERT INTO Cards(Questions)
    VALUES($value)";
    mysqli_query($con,$newcards);
    }

mysqli_close($con);
?>

It just doesn't add anything to my database.它只是没有向我的数据库添加任何内容。 How should I go about doing this?我该怎么做呢? I am new to PHP and SQL and can't seem to figure this out.我是 PHP 和 SQL 的新手,似乎无法弄清楚这一点。

Given:鉴于:

<input type="text" name="foo[]" />
<input type="text" name="foo[]" />
etc...

in your form, you'd loop over them with在你的表单中,你会用

foreach($_POST['foo'] as $index => $value) {
    ...
}

The [] in the field name will be stripped off by PHP and used as a hint that it should expect multiple values with the same name, causing it to create a sub-array inside $_GET/$_POST to accomodate those extra values.字段名称中的[]将被 PHP 剥离并用作暗示它应该期望多个具有相同名称的值,从而导致它在 $_GET/$_POST 中创建一个子数组来容纳这些额外的值。

You can also suggest which array keys PHP should use, eg您还可以建议 PHP 应该使用哪些数组键,例如

<input type="text" name="foo[1]" value="hi there" />
<input type="text" name="foo[abc]" value="TGIF!" />

echo $_POST['foo'][1]; // outputs "hi there"
echo $_POST['foo']['abc'] // outputs "TGIF!"

Multi-dimensional arrays are also supported, using the same notation/access methods.也支持多维数组,使用相同的表示法/访问方法。

you can assign input names like he following(using javascript) and create a hidden field that contains the number of field, so when the user add more input fields, the hidden field is updated dynamically.您可以像下面这样分配输入名称(使用javascript)并创建一个包含字段数量的隐藏字段,因此当用户添加更多输入字段时,隐藏字段会动态更新。

<input name="field_1">
<input name="field_2">
<input name="field_3">
<input type="hidden" name="count" value="3">

so when you post this you know how many fields you have.所以当你发布这个时,你知道你有多少个字段。

OK.行。

  1. First of all, $value is never defined.首先, $value 从未定义。
  2. This code is a security risk because you need to sanitize your input before inserting into the database.此代码存在安全风险,因为您需要在插入数据库之前清理输入。
  3. use $_GET or $_POST depending on how your form is set.根据表单的设置方式使用 $_GET 或 $_POST 。 $_REQUEST probably also includes information you wont need $_REQUEST 可能还包括您不需要的信息
  4. Not sure what your database looks like.不确定您的数据库是什么样的。 Should each form field be a separate row or a separate column?每个表单字段应该是单独的行还是单独的列? Your code seems to do the former, but it sounds like you'd want the latter?您的代码似乎是前者,但听起来您想要后者? If it's the latter then you really would need to name your form inputs like Amir Noori noted.如果是后者,那么您真的需要像 Amir Noori 指出的那样命名您的表单输入。

    Assuming you have a form like that:假设你有一个这样的表格:

     <form method="POST" action="myphp.php`> <input type="text" name="column_name_one" /> <input type="text" name="column_name_two" /> <input type="text" name="column_name_three" /> <input type="submit" name="submit" value="submit" />

    then然后

     <?php if (isset $_POST['submit'] { $con=mysqli_connect("","test","test","Flashcards"); $values = array(); $columns = array(); foreach($_POST[] as $key => $value) { if (!empty($key) && $key != "submit") { $values[] = $con->real_escape_string($value); $columns[] = $con->real_escape_string($key); } } $colStr = implode(",",$columns); $valStr = implode("','",$values); $myQuery = "INSERT INTO Cards($colStr) VALUES ('$valStr'); if (!$con->query($myQuery)) { echo "Error Occured: $con->error"; } } ?>

Now this only works when your column names are the same as your form input names.现在这仅在您的列名称与表单输入名称相同时才有效。 Also assumes they are all strings (varchar etc).还假设它们都是字符串(varchar 等)。 If this is not the case then you need to handle that by simply accessing the form fields individually by name.如果不是这种情况,那么您需要通过简单地按名称单独访问表单字段来处理该问题。 One simple way:一种简单的方法:

       <?  

          if (isset($_POST['name']) && !empty($_POST['name']) {   //name field maps to cName column varchar
            $colStr = "cName,";
            $valStr = "'" . $_POST['age'] . "',";  //need quotes
          }

          if (isset($_POST['age']) && !empty($_POST['age']) {   //age field maps to customerAge column numeric
            $colStr .= "customerAge,";
            $valStr .= $_POST['age'] . ",";       //no quotes
          }          
        ?>

Or use array_map() to map an array of column names to form fields.或者使用array_map()将列名数组映射到表单字段。 Something like that might also help if you need to make sure all the post variable names are really valid column names and someone isn't trying to send you garbage.如果您需要确保所有 post 变量名称都是真正有效的列名称,并且没有人试图向您发送垃圾邮件,那么类似的事情也可能会有所帮助。 Obviously the insert will fail if the column names aren't correct but usually it's better not to let it even try to insert a bad query.显然,如果列名不正确,插入将失败,但通常最好不要让它尝试插入错误的查询。

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

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