Reputation: 23
I pulled down an array of business services from my server and wanted to display the data in a form so it could be edited and sent to another page.
I wanted to assign a variable to each piece of data (ie. input type ='text' name='service$c') and iterate the value of $c so that it would assign a new value each time (ex. service1, service2, etc.) so that when the data posted to the next page I could retrieve it by those variable names.
I found that if I put something like " for ($i=1; $i<20 $i++) "inside the while loop, each individual bit of data in my array would print 20 times and if I took it outside of the while loop, the while loop $c would equal "service1" each time.
I did work out a solution, but I'm wondering if it's kind of hackey...It works, but I'm wondering if I could have done it better.
//Create the form
echo "<form action='changeservices2.php' method='post'>";
//Print Out My Array
while ($result_ar = mysqli_fetch_assoc($result)) {
//Shorten the variable
$a=$result_ar['service'];
//Start at 1
$b=1;
//Iterate
$c = $b+$d;
echo "<input type ='text' name='service$c' value='$a' ><br>";
//Since the first variable is null, I needed to help change it
if (is_null($c)) {$c=1;}
$d=$c;
}
echo "<input type ='submit' value='submit' ><br>";
echo "</form>";
It works, I'm just wondering if I'm missing a more elegant / simple solution
Upvotes: 0
Views: 152
Reputation: 780871
Use array-style names:
<input type="text" name="service[]" value="$a">
Then $_POST['service']
will be an array that you can loop over.
Upvotes: 2