tags:

views:

75

answers:

3

i have an example here of two arrays from the form,

<input type="text" name="children[]" />
<input type="text" name="age[]" />

my problem is to insert the value above in the same table like

insert into childTable(children,age) values('children[]','age[]')

it's in the form of array coz i don't know how many children to input.. can u help me to solve this???? any answers will be highly appreciated...thank you!!!

A: 

I think you need a for loop.

Pseudo code:

for(int i = 0; i < children.Length; i++)
{
    insert into childTable(child, age) values(children[i], ages[i])
}
Jonathan Parker
+2  A: 

The data from your form will be accessible in PHP in the $_POST variable (or $_GET, but you should probably use $_POST, eg: <form method="post">).

The first thing I usually do after designing a form, is to post it back to the script and add this line:

print_r($_POST);

This will show you the structure of the data you're working with. In your case it will look something like this:

array(
    "children" => array(
        0 => "Bobby",
        1 => "Mary",
        2 => "Janey"
    ),
    "age" => array(
        0 => 8,
        1 => 12,
        2 => 7
    )
);

(I assume there's a corresponding age field for each children field, yeah?)

Therefore it's just a matter of looping through the array thusly:

$numKids = count($_POST['children']);
$values = array();

for ($i = 0; i < $numKids; ++$i) {
    $values[] = "('" . mysql_real_escape_string($_POST['children'][$i]) . "'"
              . ", " . intval($_POST['age'][$i]) . ")";
}
$sql = "INSERT INTO `childTable` (`children`, `age`) "
     . "VALUES " . implode(",", $values);
nickf
A: 

Multiple value form fields aren't really intended to be used for matching fields like that. There's no guarantee provided that multiple $_POST['children'] and $_POST['age'] values will end up submitted in the same order, or even with the same number of elements.

You'd be better off using a series of numbered fields, like:

Child 1:    
<input name="children_1" />
<input name="age_1">
<br />
Child 2:
<input name="children_2" />
<input name="age_2" />
...

Then use code such as this to iterate through submitted values:

$i = 1;
while (isset($_POST['children_' . $i]) && isset($_POST['age_' . $i])) {
    if ($_POST['children_' . $i] != '') {
        mysql_query('insert into childTable (children, age) values (\''
           . mysql_real_escape_string($_POST['children_' . $i]) . '\', \''
           . mysql_real_escape_string($_POST['age_' . $i]) . '\')');
    }
    $i++;
}

Of course in the real world, you'll also want to add some validation to check that these values make sense before you insert them into your database.

Tobias Cohen
you can specify their index in the HTML: <input name="children[0]" /> <input name="children[1]" />
nickf