Could someone tell how to write this insert into a database? The below code is an example of what I am trying to accomplish. I want to have a form for families with multiple children. They submit their family names and one id that they will share in the database. See code below...
FORM INPUTS
<input type="text" name="fname[]"/>
<input type="text" name="lname[]"/>
<input type="text" name="fname[]"/>
<input type="text" name="lname[]"/>
<input type="text" name="family_id"/>
This is where I am having troubles. I can submit the family names but only the first(row) "name" is storing the "family_id" as well.
PHP
foreach($_POST['fname'] as $key => $fname) {
$lname = $_POST['lname'][$key];
$family_id = $_POST['family_id'][$key];
$query = mysql_query("INSERT INTO Table (FName, LName, Family_ID ) VALUES ('{$fname}', '{$lname}', $_POST['family_id'])");
}
I appreciate any help!
Missing {}
around $_POST['family_id']
.
family_id
insn't an array.
So the first iteration you get
$_POST['family_id'][0]; // gets the id
The second
$_POST['family_id'][1]; // gets undefined index
To fix it do the following.
Add the following code before foreach
loop and concat $family_id
to the query like you did with the others.
$family_id = $_POST['family_id'];
Try this:
extract($_POST);
$total=count($fname);
for($i=0;$i<count($total);$i++)
{
$fname=$fname[$i];
$lname=lfname[$i];
$query="INSERT INTO Table (FName, LName, Family_ID ) VALUES ('{$fname}', '{$lname}', $family_id)";
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.