mysqlarraysfor-loopforeachmultiple-insert

Insert, update or delete in multiple row form


I need to known how can I make a INSERT, UPDATE or DELETE in multiple rows if in the invoice form I make some changes in products like edit one, delete others or add new ones with one query... I tried with the update but if I delete one or two products or if I add one or two and save the form, in the DB the changes are not made, only the data that previously are in the DB was updated.

Here my code:

            if (!empty($_POST)) {
                $conn->beginTransaction();
                $stmt = $conn->prepare("UPDATE PRODUCTOS SET `cod` = :cod, `nombreProd` = :nombreProd, `proveedor` = :proveedor, `existencia` = :existencia, `ref_compra` = :ref_compra 
                WHERE `id_p` = :id_p");
                $stmt->bindParam(":cod", $cod, PDO::PARAM_STR);
                $stmt->bindParam(":nombreProd", $nombreProd, PDO::PARAM_STR);
                $stmt->bindParam(":proveedor", $proveedor, PDO::PARAM_STR);
                $stmt->bindParam(":existencia", $existencia, PDO::PARAM_STR);
                $stmt->bindParam(":ref_compra", $ref_compra, PDO::PARAM_STR);
                $stmt->bindParam(":id_p", $id_p, PDO::PARAM_INT);

                foreach ($_POST['id_p'] as $i => $id_p) {
                    $cod = $_POST['cod'][$i];
                    $nombreProd = $_POST['nombreProd'][$i];
                    $proveedor = $_POST['proveedor'][$i];
                    $existencia = $_POST['existencia'][$i];
                    $ref_compra = $_POST['ref_compra'];
                    $id_p = $_POST['id_p'][$i];
                    $stmt->execute();
                }
                $conn->commit();
            }

EDIT

Here is my multiple insert code:

            $conn->beginTransaction();
            $sql = "INSERT INTO PRODUCTOS
            (cod, nombreProd, proveedor, existencia, compra, tCompra, f_vencimiento, id_user, nombre, ref_compra, f_compra)
             VALUES ";
            $insertQuery = array();
            $insertData = array();
            foreach ($_POST['cod'] as $i => $cod) {
                $insertQuery[] = '(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)';
                $insertData[] = $_POST['cod'][$i];
                $insertData[] = $_POST['nombreProd'][$i];
                $insertData[] = $_POST['proveedor'][$i];
                $insertData[] = $_POST['existencia'][$i];
                $insertData[] = $_POST['compra1'][$i];
                $insertData[] = $_POST['total1'][$i];
                $insertData[] = $_POST['f_vencimiento'][$i];
                $insertData[] = $_POST['id_user'];
                $insertData[] = $_POST['nombre'];
                $insertData[] = $_POST['ref_compra'];
                $insertData[] = $_POST['fecha'];
            }
            if (!empty($insertQuery)) {
                $sql .= implode(', ', $insertQuery);
                $stmt = $conn->prepare($sql);
                $stmt->execute($insertData);
            }
            $conn->commit();

Solution

  • Here's how to combine the INSERT and UPDATE codes. The form should have an empty id_p field in rows that are being inserted. This code replaces that with NULL in the INSERT, which tells the DB to assign it using auto-increment. The ON DUPLICATE KEY clause uses the VALUES() function to get the values from the row being inserted.

           $conn->beginTransaction();
            $sql = "INSERT INTO PRODUCTOS
            (id_p, cod, nombreProd, proveedor, existencia, compra, tCompra, f_vencimiento, id_user, nombre, ref_compra, f_compra)
             VALUES ";
            $insertQuery = array();
            $insertData = array();
            foreach ($_POST['cod'] as $i => $cod) {
                if (isset($_POST['delete']) && in_array($_POST['id_p'][$i], $_POST['delete'])) {
                    // Skip rows that are being deleted
                    continue;
                }
                $insertQuery[] = '(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)';
                $insertData[] = $_POST['id_p'][$i] == '' ? null : $_POST['id_p'][$i];
                $insertData[] = $_POST['cod'][$i];
                $insertData[] = $_POST['nombreProd'][$i];
                $insertData[] = $_POST['proveedor'][$i];
                $insertData[] = $_POST['existencia'][$i];
                $insertData[] = $_POST['compra1'][$i];
                $insertData[] = $_POST['total1'][$i];
                $insertData[] = $_POST['f_vencimiento'][$i];
                $insertData[] = $_POST['id_user'];
                $insertData[] = $_POST['nombre'];
                $insertData[] = $_POST['ref_compra'];
                $insertData[] = $_POST['fecha'];
            }
            if (!empty($insertQuery)) {
                $sql .= implode(', ', $insertQuery);
                $sql .= " ON DUPLICATE KEY UPDATE
                        cod = VALUES (cod), nombreProd = VALUES (nombreProd), proveedor = VALUES (proveedor), existencia = VALUES (existencia), ref_compra = VALUES (ref_compra)"
                $stmt = $conn->prepare($sql);
                $stmt->execute($insertData);
            }
            $conn->commit();
    

    For deletions, you should have a Delete checkbox in each row:

    Delete <input type="checkbox" name="delete[]" value="$row[id_p]">
    

    Then you can delete them in one query with:

    if (!empty($_POST['delete'])) {
        $sql = "DELETE FROM PRODUCTOS WHERE id_p IN (";
        $sql .= str_repeat("?, ", count($_POST['delete']) - 1);
        $sql .= "?)";
        $stmt = $conn->prepare($sel);
        $stmt->execute($_POST['delete']);
    }