如何循环遍历表单中的输入数组? [英] 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']
}
我也试过这个:
<?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);
?>
它只是没有向我的数据库添加任何内容.我该怎么做呢?我是 PHP 和 SQL 的新手,似乎无法弄清楚这一点.
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.
推荐答案
鉴于:
<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) {
...
}
字段名中的[]
将被PHP剥离并用作提示它应该期望多个具有相同名称的值,从而导致它在$_GET内部创建一个子数组/$_POST 来容纳这些额外的值.
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 应该使用哪些数组键,例如
You can also suggest which array keys PHP should use, e.g.
<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.
这篇关于如何循环遍历表单中的输入数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!