PHP form data handling

  • mindfullsilence
  • Professor
  • Professor
  • User avatar
  • Posts: 854

Post 3+ Months Ago

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?
  • Anonymous
  • Bot
  • No Avatar
  • Posts: ?
  • Loc: Ozzuland
  • Status: Online

Post 3+ Months Ago

  • joebert
  • Fart Bubbles
  • Genius
  • User avatar
  • Posts: 13502
  • Loc: Florida

Post 3+ Months Ago

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.
  • mindfullsilence
  • Professor
  • Professor
  • User avatar
  • Posts: 854

Post 3+ Months Ago

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?
  • joebert
  • Fart Bubbles
  • Genius
  • User avatar
  • Posts: 13502
  • Loc: Florida

Post 3+ Months Ago

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)

Post Information

  • Total Posts in this topic: 4 posts
  • Users browsing this forum: No registered users and 120 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
 
cron
 

© 1998-2014. Ozzu® is a registered trademark of Unmelted, LLC.