Nilsson1188
Nilsson1188

Reputation: 25

Foreach input php and mysql

I know there are similar topics out there but haven't been able to find what I'm looking for. So what I need to do is target a specific input name and foreach loop only that input instead of the whole form.

HTML look something like below.

        <form action"<?php echo $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data" name="table1" method="post">
            <input name="something1" type="text" />
            <input name="something2" type="text" /> 
            <input name="something3" type="text" />
            <input name="something4" type="text" />
            <input name="something4" type="text" />
            <input name="something4" type="text" /> 
            <input name="button"  type="submit" value="Add" />    
        </form>

So I wanna loop every "something4" and just ignore the rest. Is this possible?

Just to explain what I want to do with the value is for every "something4" I'm gonna add a field to my DB and the input the respective input value into that field.

something like below...

        $i = 0;
        foreach ($_POST as $something4 => $something4_value) {
            $add = mysqli_query($connect, "ALTER TABLE 'table' ADD something4$i VARCHAR( 255 ) NOT NULL") or die (mysql_error());
            $sql_update = mysqli_query($con, "UPDATE 'table' SET something4$i='$something_value' WHERE id='$id'") or die (mysql_error());
            $i++;
        }

I hope this make sense! Thank you! :)

Upvotes: 0

Views: 3761

Answers (1)

Geoff Atkins
Geoff Atkins

Reputation: 1703

Create each of the name="something4" into an array like this:

<input name="something4[]" type="text" />

Then you can do a

foreach($_POST['something4'] as $something4) {
}

Upvotes: 2

Related Questions