Jump to content

For Loop


verdrm

Recommended Posts

I have a form that has fields like this:

 

<input name = "Name[]">

 

I want to insert that into a record, so I use this:

 

foreach($_POST['Name'] as $val){

 

$query = mysql_query("INSERT INTO `table` etc.

 

}

 

If I want to add something else to that query, such as this:

 

foreach($_POST['Name'] as $val){

    foreach($_POST['ID'] as $id){

 

$query = mysql_query("INSERT INTO `table` etc.

 

}}

 

 

...the script now inserts four rows instead of one, because it loops through for each field. I only want one record in this particular case. How can I take data from an array such as Name[] and insert it?

 

Link to comment
https://forums.phpfreaks.com/topic/101246-for-loop/
Share on other sites

I'm not completely sure I understand, but if you're looking to grab the matching ID as Name, you would need to just get the key of the name you're after and pull the same ID:

<?php
foreach ($_POST['Name'] as $k => $v)
{
  $name = $_POST['Name'][$k];
  $id = $_POST['ID'][$k];
}
?>

Link to comment
https://forums.phpfreaks.com/topic/101246-for-loop/#findComment-517883
Share on other sites

No, sorry, what I meant was that I have a form with Javascript, that when you click the Javascript link it adds a new field to the form.

 

So, the form starts with one Name field, then you click a link and another Name field appears. You can add as many Name fields as you want. The input name is Name[]

 

My form collects Name[] to insert into the database using this:

 

foreach($_POST['Name'] as $val){

 

$query = mysql_query("INSERT INTO `table` etc.

 

}

 

My problem is that now I have another field ID which can be duplicated as much as the user wants. Now I have this:

 

 

foreach($_POST['Name'] as $val){

 

    foreach($_POST['ID'] as $val2){

 

$query = mysql_query("INSERT INTO `table` etc.

 

}}

 

The problem with the code above is that while gets all the stuff from Name[] and ID[], it inserts it more than once, maybe four times, because it goes through the loop for each instead of doing it once if there is only one Name[] field and one ID[].

 

Link to comment
https://forums.phpfreaks.com/topic/101246-for-loop/#findComment-517891
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.