通过PHP和MySQL插入数据

时间:2017-08-30 16:56:07

标签: php mysql

它正在工作,但是当我将数据添加到我的数据库时,数据将是两次。我不知道我的语法是错误的还是我的代码错了。

这是结构:

//if submit is clicked
$checkin = $_POST['text_checkin'];
while ($row = mysqli_fetch_array($reservation)) { 
    if (isset($_POST['submitBtn'])) {
        if ($row['reservefrom'] == $checkin) { 
            echo "Same Date";
            return;
        }  
        else
        {
            $lastname = $_POST['text_lastname'];
            $firstname = $_POST['text_firstname'];
            $address = $_POST['text_address'];
            $tnumber = $_POST['text_tnumber'];
            $cnumber = $_POST['text_cnumber'];
            $email = $_POST['text_email'];
            $checkin = $_POST['text_checkin'];
            $checkout = $_POST['text_checkout'];
            $room = $_POST['text_room'];
            $tour = $_POST['text_tour'];
            $guest = $_POST['text_guest'];

            $query = "INSERT INTO reservation 
                            (lastname, firstname, homeaddress, 
                            telephonenumber, cellphonenumber, email, 
                            reservefrom, reserveto, room, tour, 
                            guestnumber) 
                    values ('$lastname', '$firstname', '$address', 
                            '$tnumber', '$cnumber', '$email', '$checkin', 
                            '$checkout', '$room', '$tour', '$guest')";

            mysqli_query($db, $query);
            echo "Data Submitted!";
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您正在获取多个插入内容,因为您正在$reservations中为每个记录进行循环。如果您只预计一次记录预订,首先应该查看为什么要获得多条记录。

除此之外,通过将while循环替换为:

来更改代码
if(isset($_POST['submitBtn']) && $row = mysqli_fetch_array($reservation)){

  if($row['reservefrom'] == $checkin) die("Same Date");

  $lastname = $_POST['text_lastname'];
  $firstname = $_POST['text_firstname'];
  // ... other values, then execute your query  

}else{
  // either submitBtn was not posted or no result were found in $reservation
}

我还注意到您在代码中使用return,但代码似乎不在函数中,因此令人困惑。如果它在一个函数内,那么echo从内部可能是一个坏主意,除非该函数专门用于将数据直接发送到浏览器。