php - Nested input fields (parent and child structure) -


i in real tricky situation have page allows records inputted , there parent/child structure (or records/sub-records if call it). many records/sub-records can added dynamically (the rows cloned , inserted after next row) when user needs 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 sub-record</span> </div> <span class="add-record">add record</span>  

the problem on php side, when have 2 loops, 1 in loop this:

for($i = 0; $i < count($_post['parent-record']); $i++) {     $sql = "insert 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 records (input, parent) values('" . $_post['child-record'][$j] . "', '" . $parent_id . "')"; // insert $parent_id record because record child of parent.         $result = $db->sql_query($sql);     } } 

however, when process has done, each child has parent of first main record, when add 2-3 main records (not child records) like:

+------+---------+----------+ | id   | input   | parent   | +------+---------+----------+ | 1    | random  | 0        | <- indicates parent | 2    | random1 | 1        | <- child record, parent record id: 1 | 3    | random2 | 1        | <- child record, parent record id: 1 | 4    | random3 | 1        | <- should parent, it's added child | 5    | random4 | 1        | <- 1 +------+---------+----------+ 

i need kind of solution how work when creating nested input form child have parent id of record block.

your problem lies in way in iterating on records. start inserting first parent record. then, iterate on all child records--including child records belong different parents. example, take following user input:

parent1   child1a   child1b parent2   child2a 

this generate following $_post array:

$_post['parent-record'] = array('parent1', 'parent2'); $_post['child-record'] = array('child1a', 'child1b', 'child2a'); 

so, can see that, after insert parent1 database, insert child records, incorrectly assigns parent1 child2a's parent.

you need way of determining children belong parent.

and remember encode user input before inserting sql query!!

$sql = "insert records (input) values ('" . mysql_real_escape_string($_post['parent-record'][$i]) . "')"; 

Comments

Popular posts from this blog

c# - how to write client side events functions for the combobox items -

exception - Python, pyPdf OCR error: pyPdf.utils.PdfReadError: EOF marker not found -