如果用户从表单中选择多个选项,PHP将插入多个记录

如果用户从表单中选择多个选项,PHP将插入多个记录,php,mysql,pdo,Php,Mysql,Pdo,我知道这可能超出了本课的范围,但我真的需要帮助。我在我的网站上有一个表单供用户填写,数据库保存到MySQL数据库表中。但是,我希望当用户从表单中的选择字段中选择多个选项时,能够选择多行。我能得到任何帮助吗。我要死在这里了 <h3>Create Order</h3> <form action="" method="post"> <p>Product: <input type="text" name="product_id" value=""&g

我知道这可能超出了本课的范围,但我真的需要帮助。我在我的网站上有一个表单供用户填写,数据库保存到MySQL数据库表中。但是,我希望当用户从表单中的选择字段中选择多个选项时,能够选择多行。我能得到任何帮助吗。我要死在这里了

<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)
创建订单
产品:
数量:

类别: 名片 传单 小册子

插入“订单”(产品标识、数量、类别标识)值(产品标识、数量、类别标识)
如果用户选择多个类别,我希望订单另存为单个订单。我希望这能更好地解释

这不是一个完整的解决方案,只是一些提示,以帮助您执行 任务

您需要一些代码来处理用户输入并将其存储在数据库中,因为您有一个空的表单操作(
action=“”
),相同的脚本将用作表单提交的目标,因此您需要一些条件,如果post字段中存在一些数据,则该条件将计算为true(因为您的表单提交类型是post
method=“post”

您的脚本中应该包含一些类似以下的代码段:

<?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"> 
...

创建订单
...

谢谢@Abdo,我用它来代替它

<?php
  if(isset($_POST['product_id'])) {
     $product_id = $_POST['product_id'];
     $quantity = $_POST['quantity'];
     $category = $_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
    for ($i=0; $i<sizeof($category);$i++) {
      // construct your query here
    }
  }

?>

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

创建订单

你能详细说明一下吗?数据库结构是什么样子的?到目前为止你尝试过什么?请发布关于你的模式的详细信息+你的代码看起来如何hi@AbdoAdel,我刚刚添加了一些详细信息。感谢你的努力,删除了否决票,我现在将发布一些有帮助的观点