簡體   English   中英

根據 php 中的條件更新或插入

[英]update or insert based on a condition in php

我正在學習 php,我正在為餐廳做一個小項目。 在仆人頁面中,當我嘗試接受訂單時,首先我檢查訂單列表中是否存在食物,如果食物已經存在於表中,那么食物的數量將更新,否則如果訂單列表中不存在食物所以它會被添加到(tbl_temp_order),但它給了我錯誤。 我該如何解決? 我感謝您的幫助。

if (isset($_POST[$row['fid']])) {
    if (isset($_SESSION['tableId'])) {
        $table = $_SESSION['tableId'];
        $foodId = $row['fid'];
        $returnQTY = checkQty($foodId);
        //If the quantity was bigger than 0 in (order table) it just increases the quantity and updates the record
        $state = 0;
        if ($returnQTY) {
            $qty = '';
            $qty++;
            $updateQty = "update tbl_temp_order set qty='$qty' where fId='$foodId'";
            mysqli_query(getConnection(), $updateQty);
        } else {
            //but if the quantity for this food in (order table) was '0' so it will insert new record.
            $qty = 1;
            $insert = "insert into tbl_temp_order(fid,tid,qty,state)value ('$foodId','$table','$qty','$state')";
            mysqli_query(getConnection(), $insert);
        }
    }
}

更好的解決方案 - 使用ON DUPLICATE UPDATE查詢。 您需要使用主/唯一索引fid創建/更新表tbl_temp_order

CREATE TABLE `tbl_temp_order` (
    fid int primary key,
    tid int,
    qty int,
    state int
);

並使用下一個查詢:

insert into `tbl_temp_order` (
    `fid`, `tid`, `qty`, `state`
) values (
    ?, ?, 1, 0  /*`qty` = 1, `state` = 0 by default*/
) ON DUPLICATE KEY UPDATE `qty` = `qty` + 1;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM