UPDATE如果存在,则插入

时间:2015-04-25 13:38:31

标签: php sql

UPDATE的正确格式是什么,如果存在,则在这种情况下插入 - 我已经设法进行更新并单独插入但需要它们一起?

我想要的是 - 如果日期存在则会更新到全天,如果它不存在则会插入带有新详细信息的新行。

$date = (isset($_POST['date']) ? $_POST['date'] : null);
$reservationType = (isset($_POST['reservation-type']) ? $_POST['reservation-type'] : null);

$connect = new mysqli($servername, $username, $password, $dbname);


// check connection 

if ($connect->connect_error) {
    die("connection failed: ". $connect->connect_error);
}

$sql = "SELECT * FROM reservations";
$result = $connect->query($sql);

if ($result -> num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        if ($date == $row['date_of_reservation']) {
           "UPDATE reservations SET reservationType = 'FULLDAY' WHERE   date_of_reservation='$date'";
    }
    else {
        "INSERT INTO reservations (date_of_reservation, reservationType) VALUES ('$date', '$reservationType')";
        }
    }
}

1 个答案:

答案 0 :(得分:4)

来自the manual

INSERT INTO table (a,b,c) VALUES (1,2,3)
  ON DUPLICATE KEY UPDATE c=c+1;