php - Retrieve data from dynamically generated form

473

I'm trying to use a dynamically created form to edit content on a page. I retrieve information from a DB table (in this case image captions) and display them in text areas ready to be edited and saved back into the DB.

This seems to do the job of organizing and displaying the form:

echo"<form action='edit.php' method='post'>";
 for ($limit;$limit<=$all_values;$limit++)
     {
      echo "<textarea cols='15' rows='3' name='caption' value='$caption_arr[$limit]'>
             $caption_arr[$limit]</textarea><br>
      }
      echo "<br><input type='submit' value='Edit' name='pictureEedit'></form>";

But something goes wrong from here. When I enter this in edit.php:

 $caption=$_POST['caption'];
 echo $caption;

And I only get the caption from the last field. When I added check boxes to the form it all worked fine provided I only checked 1 but if I checked 2 or more it would only give me the value for the last one.

I also tried this:

 $caption[$x]=$_POST['caption'];
 foreach ($caption as $key => $value) {echo $key.$value.'<br>';}

but got the same result.

681

Answer

Solution:

In your form

name='caption'

has to be

name='caption[]'

And later on you can do:

foreach ($_POST['caption'] as $key => $value) {echo $key.'=>'.$value.'<br>';}
966

Answer

Solution:

You cannot use the same name for all fields. you have to make array of them. try this

 name='caption[]'

People are also looking for solutions to the problem: How to make PHP variables preserved in CSS stylesheets generated by SASS / SCSS?

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.