0

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

user3236149
  • 167
  • 4
  • 16
  • `update yourtable set id=1`? id fields are usually unique per-record, so not sure what you're trying to get al... – Marc B May 11 '15 at 18:10
  • @MarcB The `id` is for `userid` and not the `id` of `PRODUCTOS` TABLE that is unique, I need this for register which user added "x" invoice or updated "X" invoice... – user3236149 May 11 '15 at 18:16

1 Answers1

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
            }
Dan
  • 10,614
  • 5
  • 24
  • 35