如果已存在于数据库中则更新现有数组记录,否则使用数组插入数据库

时间:2017-07-16 08:02:46

标签: php mysql arrays

我在使用每个销售订单更新时收到错误。

    foreach( $_POST['productId'] as $key => $val){
            $invoice_arrs = array(
                    "product_name"      =>      $_POST['productname'][$key],
                    "purchaseQty"       =>      $_POST['purchaseQty'][$key],
                    "sellingPrice"      =>      $_POST['sellingPrice'][$key],
                    "discount"          =>      $_POST['discount'][$key],
                    "dis_type"          =>      $_POST['discounttype'][$key],
                    "total"             =>      $_POST['total'][$key],
                    "net_price"         =>      $_POST['net_price'][$key]
            );
$temp=UpdateRecords("sales_order","sales_order_id=$id",$invoice_arrs,1);

   //here is my update record function

    function UpdateRecords($table, $condition, $updata, $debug = "") {
    global $conn;

    foreach ( $updata as $key => $value ) {
        if ($value != "now()") {
            $fv [] = "$key = \"" . "$value" . "\"";
        } else {
            $fv [] = "$key = " . "$value" . "";
        }
    }

    $fv_list = trim ( implode ( ", ", $fv ) );
    $query = "UPDATE $table SET " . "$fv_list" . " WHERE $condition";
    if ($debug == 1) {
        echo $query;
    }

    $result = executeQuery( $query );

    if (! mysqli_affected_rows ( $conn )) {
        global $errormessage;
        $errormessage = mysqli_error ( $conn );

        if (! empty ( $errormessage ))
            return 0;
    }

    return 1;
}   

1 个答案:

答案 0 :(得分:0)

您可以尝试以下查询 -

INSERT INTO $table (product_name, 
                    purchaseQty, 
                    sellingPrice,  
                    discount, 
                    dis_type, 
                    total, 
                    net_price)
VALUES($_POST['productname'][$key],
       $_POST['purchaseQty'][$key],
       $_POST['sellingPrice'][$key],
       $_POST['discount'][$key],
       $_POST['discounttype'][$key],
       $_POST['total'][$key],
       $_POST['net_price'][$key])
ON DUPLICATE KEY UPDATE product_name = VALUES($_POST['productname'][$key]), 
                        purchaseQty = VALUES($_POST['purchaseQty'][$key]), 
                        sellingPrice = VALUES($_POST['sellingPrice'][$key]), 
                        discount = VALUES($_POST['discount'][$key]), 
                        dis_type = VALUES($_POST['discounttype'][$key]), 
                        total = VALUES($_POST['total'][$key]), 
                        net_price = VALUES($_POST['net_price'][$key]);