Jump to content

Archived

This topic is now archived and is closed to further replies.

steve m

Combining variables into an array

Recommended Posts

Hi All,

I have this problem, I'm not even sure if this can be done.  I have this form where I have a drop down list for a quantity of serial numbers.  When a user selects a numbers from that list I have some JavaScript to dynamically create the number of Text Boxes selected.  In the JavaScript, the name of the text box is serial_num and a number is added at the end of the name ex. serial_num0, serial_num1, etc...  Anyways, what I want to do is to take the serial numbers from the form and create a separate record for each in a MySQL database.

The problem I am having is that since the serial_num fields have numbers at the end of the field names I can't seem to come up with some kind of loop to separate those different serial numbers.  Is there a way I can combine all of those serial number fields into an array to try to get the results that I want?  If that can be done, I'm lost on how to do that coming from a form submission.

Share this post


Link to post
Share on other sites
Sure, rather than using javascript to call the fields serial_num0 serial_num1 etc, get it to call all the fields the same thing.  Get it to call them all [color=green]serial_num[][/color].

Then php can access them by using the following:

[code]<?php
foreach ($_REQUEST['serial_num'] as $serial){
  echo "$serial<br>\n";
}
?>[/code]

Regards
Huggie

Share this post


Link to post
Share on other sites
Create a text-field as "fields_count" and when fields are added/removed using javascript, this field value should be updated accordingly. Then you can run a loop such as this:

[code=php:0]
$fields_count = intval($_POST['fields_count']);
for ($i = 0; $i <= count($fields_count); $i++)
{
      if (empty($_POST['serial_num'.$i])) {
            continue;
      }

      // or here, do anything you like with the data now... it's in $_POST['serial_num' . $i] ....
}
[/code]

Share this post


Link to post
Share on other sites
Huggie's suggestion, IMHO, is going to be your best bet here since it won't matter how many additional fields they add. You just need to run a count() on the $_POST['serial_num'] field to see how many they submitted.

Share this post


Link to post
Share on other sites
Great! Thanks HuggieBear that did the trick. 

Thanks a lot to everyone’s comments.  That helped me out a lot!

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.