Form Loop with incremented $i Files and Input

Alright, I have tried to do this a hundred ways, read a thousand posts. Hopefully someone can steer me in the right way.

I have a form I created do display “20” fields - value is changeable.

I want to loop through the form on the process page and set a variable to each form element and check that element with the database field already filled in. This includes the names of images I want to upload.

I have this form code. Works great.


$num_of_fields=21;
for($i=1;$i<$num_of_fields;$i++)
     {
          echo'<tr><td><b>Image '.$i.'</b><br/ >
          <input type=file name=file'.$i.' class=bginput><td><b>Image Title '.$i.'</b><br />
            <input type=text name=filetitle'.$i.' size=40 value='.$data['filetitle'.$i.''].'></td></tr>
            <tr><td><img src="/image.php/'.$data['file'.$i.''].'?width=100&amp;height=100&amp;image=/images/'.$data['file'.$i.''].'" alt="" /></td>
              <td><b>Image Description '.$i.'</b><br />
               <textarea cols=50 rows=5 name=filedesc'.$i.'>'.$data['file'.$i.'desc'].'</textarea>
                  </td></tr>';
                                }

On submit it gets posted to a process page…

How do I loop through this data and assign the variable to the form content submitted. As you can see the form element name is incremented by $i.

Hope this makes sense.

This code creates an associative array ($var) in the form processing script whose key is the element name and value equals the value submitted in each textbox.

index.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title></title>
    </head>
    <body>

        <form action="procForm.php" method="post" >
            <input type="textbox" name="txt1" />
            <input type="textbox" name="txt2" />
            <input type="textbox" name="txt3" />
            <input type="textbox" name="txt4" />
            <input type="submit" value="Submit" />
        </form>
    </body>
</html>

procForm.php

<?php

    $varNames = array_keys($_POST);

    $var = array();
    
    //transfer form data to an associative array
    foreach($varNames as $value) {
        $var[$value] = $_POST[$value];
    }
     
    //display the sent form data
    foreach($var as $key=>$value) {
        echo '$var["'.$key.'"] = '.$value.'<br />';
    }


?>

Instead of implementing them as txt1, txt2, txt3…

You can make it easier on yourself by making the html fields an array.


<?php

if (isset($_POST['submit']) && is_array($_POST['form'])) {
	var_dump($_POST['form']);
/*
array(4) {
	[0]=>
	string(5) "Hello"
	[1]=>
	string(5) "World"
	[2]=>
	string(3) "Foo"
	[3]=>
	string(3) "Bar"
}	
*/
}

?>

<!DOCTYPE html>
 <html>
	<head>
		<title></title>
    </head>
	<body>
		<form  method="post" >
			<input type="text" name="form[]" />
			<input type="text" name="form[]" />
			<input type="text" name="form[]" />
			<input type="text" name="form[]" />
			<input type="submit" name="submit" value="Submit" />
		</form>
	</body>
</html>

Yes that’s another way to do it, but in this case it would be easier for me to use an associative array whose keys are the form’s input names rather than have an indexed array and I would have to make sure I am using the correct integer key for the form input I want to use.

You can still achieve the same results with an array:


<!DOCTYPE html>
 <html>
    <head>
        <title></title>
    </head>
    <body>
        <form  method="post" >
            <input type="text" name="form[name1]" />
            <input type="text" name="form[name2]" />
            <input type="text" name="form[name3]" />
            <input type="text" name="form[name4]" />
            <input type="submit" name="submit" value="Submit" />
        </form>
    </body>
</html>

One of the reasons why arrays were “invented” was so you don’t have to name something such as name1, name2, name3 and so on. There is no reason to name anything name1, name2, name3 - it’s really unreadable and you have to come up with silly ways to iterate trough it. Sure, it’s possible to iterate trough elements even if they are named like that, but why would you make it harder on yourself?

I personally prefer YaderBH’s proposed solution, and I’d definitely go with that one.

There is nearly always more than 1 to do things. I posted the easiest way for me to do it using an associative array server side.

Even tho I am all in for “new” ways of doing things, I can’t bring myself to see how is looping twice easier way than looping once, but I guess it’s just me :slight_smile:

I use only 1 loop with 1 line of code in it to transfer the form data to an associative array. If you understand and run the code I posted earlier you will see the second loop is used only as a debugging tool to display the values in the associative array and it would not normally appear in production code, unless of course the form data needs to be echoed out for some reason.

So the actual production code would be something like this

<?php
 
    $varNames = array_keys($_POST);
 
    $var = array();
    //transfer form data to an associative array
    foreach($varNames as $value) {
        $var[$value] = $_POST[$value];
    }

?>

You’re invoking array_keys too, and that function doesn’t magically know what the array keys are, does it? :slight_smile:

array_keys returns the keys of the input array.

array_keys() returns the keys, numeric and string, from the input array.

The code I posted in my original post works without any problems on my local xampp server.

I didn’t say your code doesn’t work, I said your approach is unorthodox and when compared to regular approach with naming elements (AND variables), your approach is bad.
In order for it to work, not only do you need to name your elements in the most horrible way possible, you need to invoke a function that actually INTERNALLY loops trough the array to obtain its keys. You think that all native array functions are magic and pull stuff out of thin air or what? You loop the array twice, you’re using the wrong approach (arrays were made so you can group elements of similar names together for iteration) and hey, you don’t even want to take a second and think whether your approach is POSSIBLY worse than the alternative that YaderBH posted.

I never said your code doesn’t work, I just wanted to point out it’s bad practice without trying to create ill atmosphere in the topic.

Now, you cannot argue with me on that. Sure, there’s tons of examples where badly written code does the job but that still doesn’t mean it’s not bad.
Your code isn’t bad as the codes I’ve seen, but using such practices with naming can lead towards creating bad code. It’s good to be consistent in everything, from the way of naming variables and functions to logical distribution of tasks among functions and so on.

Now if I insulted you in any way - I apologize, but I just wanted to point out bad practice that I spotted.

No problem :slight_smile: I’m not insulted at all because everyone is entitled to their view.

I’m not sure why you would think I might feel insulted because some complete stranger thinks my code is bad because I don’t see how what complete strangers think of my code can make any difference to me. In forums like this it’s not always possible to determine with total surety if I am talking to a 16 year old kid who thinks they know it all or an actual guru with years of experience, so I take the easy way out and not take offence at anything posted about my code :slight_smile:

Imv it’s not bad code and what is or isn’t bad code can in many cases be subjective.