I am in a real tricky situation where I have a page that allows records to be inputted and there is a parent/child structure (or records/sub-records if you call it). Many records/sub-records can be added dynamically (the rows are cloned and inserted after the next row) when the user needs to add more.
The structure:
<div class="row">
<strong>Parent record:</strong> <input type="text" name="parent-record[]" />
<div class="row">
<strong>Child record:</strong> <input type="text" name="child-record[]" />
</div>
<span class="add-subrecord">Add another sub-record</span>
</div>
<span class="add-record">Add another record</span>
The problem on the PHP side, when I have 2 for loops, 1 in a for loop like this:
for($i = 0; $i < count($_POST['parent-record']); $i++)
{
$sql = "INSERT INTO records (input) VALUES ('" . $_POST['parent-record'][$i] . "')";
$result = $db->sql_query($sql);
$parent_id = $db->sql_nextid(); // mysql_insert_id
for($j = 0; $j < count($_POST['child-record']); $j++)
{
$sql = "INSERT INTO records (input, parent) VALUES('" . $_POST['child-record'][$j] . "', '" . $parent_id . "')"; // this will also insert the $parent_id into this record because this record is a child of a parent.
$result = $db->sql_query($sql);
}
}
However, when the process has done, each child has a parent of the first main record, even when I add 2-3 main records (not child records) so like:
+------+---------+----------+
| id | input | parent |
+------+---------+----------+
| 1 | random | 0 | <- indicates it is a parent
| 2 | random1 | 1 | <- child record, parent is record id: 1
| 3 | random2 | 1 | <- child record, parent is record id: 1
| 4 | random3 | 1 | <- this should be a parent, but it's added as a child
| 5 | random4 | 1 | <- this one too
+------+---------+----------+
I need some kind of solution how this will work when creating nested input form that all child have a parent id of the record block.
Your problem lies in the way in which you are iterating over the records. You start by inserting the first parent record. Then, you iterate over all child records–including the child records that belong to different parents. For example, take the following user input:
This will generate the following $_POST array:
So, you can see that, after you insert
parent1into the database, you then insert all the child records, which incorrectly assignsparent1aschild2a‘s parent.You need a way of determining which children belong to what parent.
AND REMEMBER to encode your user input before inserting it into a SQL query!!