Note that there are some explanatory texts on larger screens.

plurals
  1. PONested input fields (parent and child structure)
    text
    copied!<p>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.</p> <p><strong>The structure</strong>:</p> <pre><code>&lt;div class="row"&gt; &lt;strong&gt;Parent record:&lt;/strong&gt; &lt;input type="text" name="parent-record[]" /&gt; &lt;div class="row"&gt; &lt;strong&gt;Child record:&lt;/strong&gt; &lt;input type="text" name="child-record[]" /&gt; &lt;/div&gt; &lt;span class="add-subrecord"&gt;Add another sub-record&lt;/span&gt; &lt;/div&gt; &lt;span class="add-record"&gt;Add another record&lt;/span&gt; </code></pre> <p>The problem on the PHP side, when I have 2 for loops, 1 in a for loop like this:</p> <pre><code>for($i = 0; $i &lt; count($_POST['parent-record']); $i++) { $sql = "INSERT INTO records (input) VALUES ('" . $_POST['parent-record'][$i] . "')"; $result = $db-&gt;sql_query($sql); $parent_id = $db-&gt;sql_nextid(); // mysql_insert_id for($j = 0; $j &lt; 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-&gt;sql_query($sql); } } </code></pre> <p>However, when the process has done, each child has a parent of the <em>first</em> main record, even when I add 2-3 <em>main</em> records (not child records) so like:</p> <pre><code>+------+---------+----------+ | id | input | parent | +------+---------+----------+ | 1 | random | 0 | &lt;- indicates it is a parent | 2 | random1 | 1 | &lt;- child record, parent is record id: 1 | 3 | random2 | 1 | &lt;- child record, parent is record id: 1 | 4 | random3 | 1 | &lt;- this should be a parent, but it's added as a child | 5 | random4 | 1 | &lt;- this one too +------+---------+----------+ </code></pre> <p>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.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload