同时将数据插入和更新到数据库

时间:2017-11-23 03:21:57

标签: php mysql

function Writeform($name,$type,$num,$abroad,$datein,$cmnd,$address,$room_name){
    global $conn;
    $query= "INSERT INTO form 
    (Guest_name, Guest_type, Guest_num, Guest_abroad, datein, Guest_CMND, Guest_Address, room_name) VALUES 
    ('$name', '$type','$num','$abroad','$datein','$cmnd','$address','$room_name')";
    if(mysqli_query($conn,$query)){
        echo " added !";
        $sql="UPDATE room r INNER JOIN form f ON r.room_name=f.$room_name SET r.room_status='not avaliable'";
        if (mysqli_query($conn, $sql)) {
            echo " Record updated successfully ";
            }
            else{
                echo "Couldn't Update !!";
            }
    }
    else{
        echo "Couldn't Add!!";
    }
}

我试图插入数据库并同时更新,但我一直在添加,无法更新!

1 个答案:

答案 0 :(得分:2)

您无需加入UPDATE查询中的表格。

$sql = "UPDATE room SET room_status = 'not available'
        WHERE room_name = '$room_name'";

但最好使用准备好的陈述。

$sql = "UPDATE room SET room_status = 'not available'
        WHERE room_name = ?";
$stmt = mysqli_prepare($conn, $sql);
mysqli_stmt_bind_param($stmt, "s", $room_name);
if (mysqli_stmt_execute($stmt)) {
    echo "Record updated successfully!";
} else {
    echo "Couldn't update!!";
}