Search code examples
mysqlarraysfor-loopforeachmultiple-insert

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


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


Solution

  • 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
                }