0

我在表单中动态地添加记录,然后我应该插入数据或更新它。我使用 ON DUPLICATE KEY UPDATE 来执行任务。一切都很好,除了每次我插入新记录或更新现有记录时,它首先复制现有记录,然后进行插入或更新。我猜查询正在使用 HTML foreach 循环中已经显示的值。我怎样才能避免这个问题?

  <?php
        foreach ($data as $ov) {                   
  ?>      

  <tr class="dataRow" id="soRows">
    <td>
        <input type="text" name="tableService" value="<?=$ov['service_type']?>" /><input type="hidden" value="<?=$ov['id_service']?>" class="id_service" name="id_service[]"/></td>
    <td>
        <input type="text" name="tableProject" value="<?=$ov['project_name']?>" /><input type="hidden" value="<?=$ov['id_project']?>"  class="id_project" name="id_project[]"/></td>
    <td>
        <input type="text" name="tableQuantity[]" value="<?=$ov['quantity']?>" /></td>          
    <td>
        <input type="text" name="tablePus[]" value="<?=$ov['unit_price_no_tax']?>" /></td>
    <td>
        <input type="text" name="tablePuc[]" value="<?=$ov['unit_price']?>" /></td>    
    <td>
        <input name="tableTotal[]" value="<?=$ov['total_item_imp']?>" /></td>
    <td>
        <i style="cursor: pointer;" class="icon-remove deleteRow"></i></td>
  </tr>

 <?php
 }  
 ?>

    for ($i = 0; $i < count($_POST['id_service']); $i++){

    $servtype = $_POST['id_service'][$i];    
    $project = $_POST['id_project'][$i];
    $quantity = $_POST['tableQuantity'][$i];
    $pus = $_POST['tablePus'][$i];
    $puc = $_POST['tablePuc'][$i];
    $totalitem = $_POST['tableTotal'][$i];
    $result1 = $_POST['labelResult'];
    $result2 = $_POST['labelResult2'];
    $id = $_POST['id'];

    $query = "INSERT INTO sales_order_items (id_soitems, id_so, id_service, id_project, quantity, unit_price_no_tax, unit_price, total_item_imp)
    VALUES
    (null,
    :id,
    :servtype,
    :project,
    :quantity,
    :pus,
    :puc,
    :totalitem
    )
    ON DUPLICATE KEY UPDATE
    id_project = :project,
    id_service = :servtype,
            quantity = :quantity,
    unit_price_no_tax = :pus,
    unit_price = :puc,
    total_item_imp = :totalitem
    ";

    $stmt = $this->dbh->prepare($query);

    $stmt->bindValue(':id', $id, PDO::PARAM_INT);
    $stmt->bindValue(':servtype', $servtype, PDO::PARAM_INT);
    $stmt->bindValue(':project', $project, PDO::PARAM_INT);
    $stmt->bindValue(':quantity', $quantity, PDO::PARAM_STR);
    $stmt->bindValue(':pus', $pus, PDO::PARAM_STR);
    $stmt->bindValue(':puc', $puc, PDO::PARAM_STR);
    $stmt->bindValue(':totalitem', $totalitem, PDO::PARAM_STR);
    $stmt->bindValue(':result1', $result1, PDO::PARAM_STR);
    $stmt->bindValue(':result2', $result2, PDO::PARAM_STR);
    $stmt->execute();

    }
4

0 回答 0