Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
426 views
in Technique[技术] by (71.8m points)

php - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...