Home > database >  How to insert 2 inputs values simultaneously using HTML Arrays & PHP POST?
How to insert 2 inputs values simultaneously using HTML Arrays & PHP POST?

Time:11-25

I am trying to pass 2 arrays in a MYSQL table using HTML array, I want to insert both values in the same row at the same time of the loop, of course nested loop isn't going to work, the first input value passed successfully, but the second input inserts wrong & unrelated values. I am sure it's because the for loop logic is incomplete, but I can't seem to adjust properly. any help will be appreciated.

HTML (...html code inside PHP then this, $row['id'] is the value that shall be passed to POST):

<input type="text" id="mytextbox" name="comment[]" placeholder = "Add your comments here" required>
<input type="text" id="mytextbox" list="decision[]" name="decision" placeholder = "Choose your decision" required>
<datalist id="decision[]">';
echo '<option value="'.htmlspecialchars($row['id']).'">'.htmlspecialchars($row['name']).'</option>';

<input type="text" id="mytextbox" name="comment[]" placeholder = "Add your comments here" required>
<input type="text" id="mytextbox" list="decision[]" name="decision" placeholder = "Choose your decision" required>
<datalist id="decision[]">';
    echo '<option value="'.htmlspecialchars($row['id']).'">'.htmlspecialchars($row['name']).'</option>';
   
<input type="text" id="mytextbox" name="comment[]" placeholder = "Add your comments here" required>
<input type="text" id="mytextbox" list="decision[]" name="decision" placeholder = "Choose your decision" required>
<datalist id="decision[]">';
    echo '<option value="'.htmlspecialchars($row['id']).'">'.htmlspecialchars($row['name']).'</option>';

PHP (after successful POST of $comment as input(1) & $decision as input(2) and working queries):

for ($i=0;$i<count($comment);$i  ){
  $query = "INSERT INTO table (otherid,col1,col2) VALUES ('$otherid','$comment[$i]','$decision[$i]')";
  $result = $dbc->query($query);
}

CodePudding user response:

You are getting only the last decision, because you did not use square brackets in the field name, as you did with the comments field. name="decision" needs to be name="decision[]". Only then will PHP create an array out of multiple passed parameters of the same name; without square brackets, they simply overwrite each other.


The duplicate IDs are only of client-side importance - selecting from those lists, will likely not populate the correct input field, but it has little to do with what actually gets submitted, if you filled those fields by hand. But you should be able to make thos IDs dynamic, for example by appending the row ID.

<datalist id="decision-123">, with a matching list="decision-123" on the input field.

  • Related