简体   繁体   中英

Send html form data to two separate tables in the database using sql and php

I have these 2 tables:

ornaments (ornament_id, ornament_name)
ornament_to_size (ornament_id, size_id, ornament_type, colour, material, finish, height, width, weight, location, price, description, image_path)

And I want to create a form in admin to insert a new ornament item into the database. What would be the best way of doing this? I need to insert in both tables which is making it more difficult for me. The ornament_id in the ornaments table is obviously the PK and the PK in the ornament_to_size table is ornament_id and size_id as a composite key.

The reason there is an ornament to size table is because an ornament can have more than one size like so:

ornament_id = 3 & size_id = 1
ornament_id = 3 & size_id = 2 
ornament_id = 3 & size_id = 3

I just want to know what the method would be not the actual code

if the size table has already got the value in it you have two choice to let the user insert the data:

  • select if you want to let the user add a single new value

  • checkboxes field if you want the user to insert more then one,
    remember to name it as 'checkboxname[]' so that php can use it as an array.

In both cases use the id of the size as value. On the Db inserting part you will have to parse the form data, then perform:

  • a Insert into the ornament table, straight after perform a LastInsertId() query (this is pdo function but you can make it in mysql too) on it and save the result in a var.
  • perform a subsequent query into the ornament_to_size table, using the var you have saved as ornament_id value.

Remember that if you have chose to use checkboxes you can just run a foreach with the $_POST['checkboxname[]'] to insert all the new rows thanks to how PhP read the POST .

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