MySQL - 插入数据或更新(如果存在)

时间:2016-06-20 11:09:12

标签: php mysql

只插入一次MySQL或更新(如果存在)。此处ticket_id是唯一键,但数据不会插入也不会更新。

 if(isset($_POST['A1'])){
        $seat_no = $_POST['A1'];
        $sql_2 = "INSERT INTO ticket_details (ticket_id,".$seat_no.") VALUES('".$ticket_id."','".$ticket_status."') ON DUPLICATE KEY UPDATE ticket_details SET ".$seat_no." = '".$ticket_status."' WHERE ticket_id = '".$ticket_id."'";     
        mysql_query($sql_2);
    }
    if(isset($_POST['A2'])) {
        $seat_no = $_POST['A2'];
        $sql_2 = "INSERT INTO ticket_details (ticket_id,".$seat_no.") VALUES('".$ticket_id."','".$ticket_status."') ON DUPLICATE KEY UPDATE ticket_details SET ".$seat_no." = '".$ticket_status."' WHERE ticket_id = '".$ticket_id."'";     
        mysql_query($sql_2);
    }

    if(isset($_POST['A3'])){
        $seat_no = $_POST['A3'];
        $sql_2 = "INSERT INTO ticket_details (ticket_id,".$seat_no.") VALUES('".$ticket_id."','".$ticket_status."') ON DUPLICATE KEY UPDATE ticket_details SET ".$seat_no." = '".$ticket_status."' WHERE ticket_id = '".$ticket_id."'";     
        mysql_query($sql_2);
    }

**这里我按照this Answer **

解决了上述代码
if(isset($_POST['A1'])){
        $seat_no = $_POST['A1'];
            $sql = "INSERT INTO ticket_details (ticket_id,".$seat_no.") VALUES('".$ticket_id."','".$ticket_status."') ON DUPLICATE KEY UPDATE  ".$seat_no." = '".$ticket_status."' ";       
            $res = mysql_query($sql);

        }
        if(isset($_POST['A2'])) {
        $seat_no = $_POST['A2'];
            $sql = "INSERT INTO ticket_details (ticket_id,".$seat_no.") VALUES('".$ticket_id."','".$ticket_status."') ON DUPLICATE KEY UPDATE  ".$seat_no." = '".$ticket_status."' ";       
            $res = mysql_query($sql);

        }
        if(isset($_POST['A3'])){
        $seat_no = $_POST['A3'];
            $sql = "INSERT INTO ticket_details (ticket_id,".$seat_no.") VALUES('".$ticket_id."','".$ticket_status."') ON DUPLICATE KEY UPDATE  ".$seat_no." = '".$ticket_status."' ";       
            $res = mysql_query($sql);
        }

1 个答案:

答案 0 :(得分:-1)

  

使用INSERT {...} ON DUPLICATE KEY UPDATE

阅读here

此外,这是一个重复的问题:Check this