简体   繁体   中英

Inserting multiple values on a form for a one to many relationship

I have two tables:

Items
- itemNumber (PK)
- title
- subject

Barcodes
- barcodeNumber (PK)
- dateAdded
- itemNumber (FK)

I have a form to read the info from the user, but I want the user to be able to insert as many barcodes for each item in the same form. How can I accomplish this with PHP and HTML?

I am attempting to have a button to submit the first barcode, but how do I make my text field to be clean and ask for the second, third, etc. I was also thinking to have this running until the user clicks on a "done" button to ask for a different item.

Please let me know if more details are needed.

Thank you!

You can send an array of barcodes like so barCodeId[]=1&barCodeId[]=2&barCodeId[]=3

Your form would look something like this

<form action="/that-post-url" method="POST">
  <input name="barCodeId[]" value="1" />
  <input name="barCodeId[]" value="2" />
  <input name="barCodeId[]" value="3" />
  <button type="submit">Submit</button>
</form> 

Then you could do a batch insert depending on whatever you're using on the backend, Laravel? Plain php mysql?

INSERT INTO table_name (field_1, field_2, field_3) VALUES(1,2,3),(4,5,6),(7,8,9);

(1,2,3) matches nubmer of fields in insert

if you need to send many values of any type via a single form you can create a form like this

View side

<form method="post" action="../myscript.php">
     <input type="hidden" name="item_id" value="1T3M_1D_1">
     <!--let's say you are sending the item_id as a hiden field-->
     <!--I will use you have the bardoces already saved to the database and
         In your form u want to display the "available" ones-->
     <--Maybe a foreach loop to create the input fields-->

     <input type="checkbox" value="BARCODE_1" name="barcodes[]">
     <input type="checkbox" value="BARCODE_2" name="barcodes[]">
     <input type="submit">
</form>

PHP side

Here we are at myscript.php where you are processing your input data, lets's say you selected both available barcodes on the form

<?php
    $itemId = $_POST['item_id'];
    $barcodes = $_POST['barcodes'];
    //this barcode as on the view had the [] at the end of the name
    //it's an array so..
    foreach ($barcodes as $item){
        //do whatever you need for each barcode
    }

Hope my answer helps you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM