PHP Insert multiple records if the user selects multiple options from the form

advertisements

I know this might be beyond the scope of this lesson but I really need help. I have a form on my website for users to fill out and the database saved into the MySQL database table. However, I want to be able to select multiple rows when a user select multiple options from the Select field in the form. Can I get any help, please. I'm dying here.

<h3>Create Order</h3>
<form action="" method="post">
<p>Product: <input type="text" name="product_id" value=""><p>

<p>Quantity:  <input type="text" name="quantity" value=""></p>

<p>Category: <select name="category" multiple>
<option value="1">Business Card</option>
<option value="2">Flyer</option>
<option value="3">Brochure</option>
</select></p>

</form>

Insert into `orders` (product_id, quantity, category_id) Value (product_id, quantity, category_id)

If the user select more than one category, I want the order to be save as individual orders. I hope this explains better.


This is not a full solution, just some hints to help you carry out the task

You need some code that handles the user input and stores it in the DB, since you have an empty form action (action=""), the same script will be used as a target for the form submission, so you need some condition that evaluates to true iff there is some data present in the post fields (since your form submit type is post method="post")

You should have some snippet like the following in your script:

<?php
if(isset($_POST['product_id'])) {
    $product_id = $_POST['product_id'];
    $quantity = $_POST['quantity'];
    $categories = $_POST['category'];
    // note that $category is an array because the attribute 'multiple' is used
    // you can loop through all selected categories and construct your query
    foreach($categories  as $category) {
       // construct your query here
    }
}

?>

<h3>Create Order</h3>
<form action="" method="post">
...