PHP form data handling

  • mindfullsilence
  • Professor
  • Professor
  • User avatar
  • Joined: Aug 04, 2008
  • Posts: 846
  • Status: Offline

Post October 17th, 2011, 5:03 pm

If you post a form that has an unknown amount of fields, how do you handle them.

I mean in a case like this:
Example

If you add several lines, and submit with post - what kind of code do you use to set the posted data into arrays? What name do you give each repeat input fields?
Use your words like arrows to shoot toward your goal.
  • Anonymous
  • Bot
  • No Avatar
  • Joined: 25 Feb 2008
  • Posts: ?
  • Loc: Ozzuland
  • Status: Online

Post October 17th, 2011, 5:03 pm

  • joebert
  • Sledgehammer
  • Genius
  • No Avatar
  • Joined: Feb 10, 2004
  • Posts: 13458
  • Loc: Florida
  • Status: Offline

Post October 17th, 2011, 5:16 pm

Give your fields names like this.

HTML Code: [ Select ]
<input name="names[]"/>
<input name="ages[]"/>
  1. <input name="names[]"/>
  2. <input name="ages[]"/>


Setup your form action to print the contents of $_GET (assuming your forms method remains as the default GET method).

PHP Code: [ Select ]
echo '<pre>', print_r($_GET, true), '</pre>';


Basically, the [] appended to the end of a form element's name will cause it to be sent as an array.
Strong with this one, the sudo is.
  • mindfullsilence
  • Professor
  • Professor
  • User avatar
  • Joined: Aug 04, 2008
  • Posts: 846
  • Status: Offline

Post October 17th, 2011, 5:34 pm

Cool, makes sense.

I'm guessing to associate the appropriate name and age inputs for each row, I just match up the indexes?

something like:
PHP Code: [ Select ]
$i = 0;
$name = $_GET["name"];
$age = $_GET["age"];
while($i < count($name)){
echo("<p>Name: $name[$i]</p><p>Age: $age[$i]</p>");
$i++;
}
 
  1. $i = 0;
  2. $name = $_GET["name"];
  3. $age = $_GET["age"];
  4. while($i < count($name)){
  5. echo("<p>Name: $name[$i]</p><p>Age: $age[$i]</p>");
  6. $i++;
  7. }
  8.  

Or something to that effect?
Use your words like arrows to shoot toward your goal.
  • joebert
  • Sledgehammer
  • Genius
  • No Avatar
  • Joined: Feb 10, 2004
  • Posts: 13458
  • Loc: Florida
  • Status: Offline

Post October 19th, 2011, 2:53 pm

In the simplest form, yes. You might want to at least make sure the array counts of each field match (ie same number of ages as names)
Strong with this one, the sudo is.

Post Information

  • Total Posts in this topic: 4 posts
  • Users browsing this forum: No registered users and 110 guests
  • You cannot post new topics in this forum
  • You cannot reply to topics in this forum
  • You cannot edit your posts in this forum
  • You cannot delete your posts in this forum
  • You cannot post attachments in this forum
 
 

© 2011 Unmelted, LLC. Ozzu® is a registered trademark of Unmelted, LLC.