How do I insert multiple value if there is only one value in form

本秂侑毒 提交于 2020-02-08 02:58:29

问题


I need to know how can I insert or update a value in my DB for a invoice form if the value of the input that I need to save is only one time?

I have a invoice form where I select a product in every row, and finally I have the input(user_id) with the value I need to save with the rest of the inputs

Like per example, I choose in the invoice:

10 tomatoes 
 5 garlics
 2 beans

and finally there is my Id (user_id, not the Id of PRODUCTOS table that is unique)

Id=1

Here is the schema of my table, and how save or update until now:

| cantidad   | nombre del producto |   Id  | 
+------------+---------------------+-------+
|     10     |   Tomatoes          |     1 |
|      5     |   garlics           |     0 |
|      2     |   beans             |     0 |

Here what I need to save or update:

| cantidad   | nombre del producto |   Id  | 
+------------+---------------------+-------+
|     10     |   Tomatoes          |     1 |
|      5     |   garlics           |     1 |
|      2     |   beans             |     1 |

Here is the code:

            $conn->beginTransaction();
            $sql = "INSERT INTO PRODUCTOS
            (cantidad, nombreProd, Id)
             VALUES ";
            $insertQuery = array();
            $insertData = array();
            foreach ($_POST['cantidad'] as $i => $cantidad) {
                $insertQuery[] = '(?, ?, ?)';
                $insertData[] = $_POST['cantidad'][$i];
                $insertData[] = $_POST['nombreProd'][$i];
                $insertData[] = $_POST['Id'][$i];
            }
            if (!empty($insertQuery)) {
                $sql .= implode(', ', $insertQuery);
                $stmt = $conn->prepare($sql);
                $stmt->execute($insertData);
            }
            $conn->commit();

Thank you


回答1:


So you have a single userID you want to INSERT for each product record. I can probably provide a better answer if you post the output of print_r($_POST), but basically in your foreach $POST loop, keep the user ID static:

foreach ($_POST['cantidad'] as $i => $cantidad) {
  $insertQuery[] = '(?, ?, ?)';
  $insertData[] = $_POST['cantidad'][$i];
  $insertData[] = $_POST['nombreProd'][$i];
  $insertData[] = $_POST['Id']; //OR $insertData[] = $_POST['Id'][0], depending on $_POST array
            }


来源:https://stackoverflow.com/questions/30174668/how-do-i-insert-multiple-value-if-there-is-only-one-value-in-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!