I have a webform where users enter names and select a "program" name from a drop down. I have a javascript function that allows the user to add boxes when they want to enter multiple names into the form. When the program is selected, and inserted into the table, a Primary Key(LINE_ID) is generated. The names are inserted into another table with then name and LINE_ID in their respective columns.
<div>
<label>Name:</label>
<tr>
<td><input type ="Text" name="yourname"/></td>
<td><input onclick="addBox(this);" type="button" value="+ Add Another Name"/></td>
</tr>
</div>
<script type="text/javascript">
var BoxNum = 0;
var NameCount = [];
function addBox(input) {
console.log(input);
BoxNum ++;
var row ='<input name = "BoxNum'+BoxNum+'">';
$(input).before(row);
NameCount.push(BoxNum);
$('#nameCount').val(NameCount);
};
</script>
The first name that appears will be entered useing the pre-existing HTML input box (1), the additional boxes will be generated by the user clicking a button (2).
<?php
$name = $_POST['yourname'];
$program = $_POST['PROGRAM_NAME'];
mysql_query("INSERT INTO prod_activity (PROGRAM_ID) (SELECT PROGRAM_ID FROM tc_program WHERE PROGRAM_NAME='$program' AND ZONE_ID=4)");
$lineid = mysql_insert_id();
// THIS WORKS:
mysql_query("INSERT INTO tc_user (USER_NAME, LINE_ID) VALUES ('$name','$lineid')");
$ElementNo = 0;
function POSTALLNAMES(){
//$ElementNo = 0;
$ElementNo ++;
$nameCount = $_POST['nameCount'];
$nameelement = explode(",", $nameCount);
$NameCountLgth = sizeof($nameelement);
foreach ($nameelement as $value){
$RealName = $_POST["BoxNum${value}"];
// THIS DOES NOT WORK:
mysql_query("INSERT INTO tc_user (USER_NAME, LINE_ID) VALUES ('$RealName','$lineid')");}}
POSTALLNAMES();
The first time I try and insert the $lineid variable with the HTML (1) box, everything is inserted into tc_user correctly. The second time I try and do it with the javascript generated input boxes (2) it does not. When I echo the variable $lineid after POSTALLNAMES(); runs, it gives the correct value for $lineid which tells me that the variable is not being reset at any point.
When I take out the LINE_ID/$lineid from the Insert statement in (2) and leave it in (1), everything inserts as you would expect (the first name with the ID and the additional names without).