简体   繁体   中英

Loop through form to update SQL Database

I am building a page that writes out a varying number of categories and then, under each category, writes out the units associated with that category. Each category section is a single form with fields that are repeated and named according to what row they belong to. The layout is like this:

Category 1

  • Unit 1 Update Fields
  • Unit 2 Update Fields
  • Unit 3 Update Fields

Submit Button for Category 1

etc.

Each field is named the same thing with the unit number added on the end:

  • Features1, Features2, Features3, etc.

The total number of rows in a given category is held in the variable $id# where # is the category's ID (ex: $id1, $id2, $id3, etc).

I've got most of this sorted out. However, I want to loop through and perform a SQL query if the form has been changed, and that's where I'm having trouble. At this point, I'm at a loss. Here is a simplified version of my code:

if (isset($_POST['submit'])) {
    $form = $_POST['form']; //save which category we're on in a variable.
    for ($i = 1; $i <= ${id.$form}; $i++) { //I think the problem is here
        $Feature = $_POST['Feature'.$i];
        $update = "UPDATE Units
               SET Feature ='$Feature'
               WHERE ID='$i'";

        if (($Feature!=${initialFeature.$i})) {
                    $updateQuery = mysqli_query($dbc, $update); 
        }
    }
}

How can I make this work? Is there a better way to do this?

The way I would do it is using an array in field names.

<input type="text" name="id[]" value="$foo">

Then on the action page for the form

$id = $_POST['id'];
for($i=0;$i<sizeof($id),$i++){
   ...//do something here using $id[$i] to select elements in the array
}

I think that is what you're trying to do.

try this

for($i=0; $i<3; $i++)
    echo '<input type="text" name="feature[]" value=""/>';
echo '<input type="submit" name="go" value="submit">';

if (isset($_POST['go'])) {
    $feature = $_POST['feature'];
    if(is_array($feature)){
        for ($i = 1; $i <= count($feature); $i++) {
            $update = "UPDATE Units
               SET Feature ='$feature[$i]'
               WHERE ID='$i'";
               $updateQuery = mysqli_query($dbc, $update); 
        }
    }else{
            $update = "UPDATE Units
               SET Feature ='$feature'
               WHERE ID='$i'";
               $updateQuery = mysqli_query($dbc, $update); 
    }

}

hope this code can solve your problem

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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