Insert two kinds of array into one table
I have an example of two arrays from a form,
<input type="text" name="children[]" />
<input type="text" name="age[]" />
my problem is to insert the value above into the same table as
insert into childTable(children,age) values('children[]','age[]')
it is as an array coz i dont know how many children to input .. can it help me to solve this? any answers would be much appreciated ... thanks !!!
The data from your form will be available in PHP in the $ _POST variable (or $ _GET, but you should probably use $ _POST like :) <form method="post">
.
The first thing I usually do after creating the form is to submit it back to the script and add this line:
print_r($_POST);
This will show you the structure of the data you are 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'm assuming there's a corresponding field age
for each field children
, yeah?)
Hence, this is just a question of how to loop through the array:
$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);
a source to share
Fields for fields with multiple values are not intended to be used to map those fields. There is no guarantee that multiple values $_POST['children']
and $_POST['age']
will be sent in the same order or even with the same number of items.
You would be better off using a series of numbered fields, for example:
Child 1:
<input name="children_1" />
<input name="age_1">
<br />
Child 2:
<input name="children_2" />
<input name="age_2" />
...
Then use code like this to iterate over the passed 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 inserting them into your database.
a source to share