Hey everyone, I have been trying to work this out for 2 days now without success. I am trying to check form input values against existing values in a column called ‘date’ in the ‘bookings’ table in the database. If any matches are found, then the whole result needs to be false so that the query wont run.
My code is such a mess of attempts, but I’m now showing the only idea that half worked.
A user chooses a date or a date range. These dates are checked against what exists in the ‘date’ column in the database. If any of the dates exist, the whole thing needs to be false, if none of the dates are found, it must be true and then those values can be saved to the database.
Here is what I have:
$sql = "
SELECT date
FROM bookings
;";
$result = $conn->query($sql);
$alreadyBooked = array();
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$alreadyBooked[] = $row['date'];
} // while
} // num rows
if(isset($_POST['submit'])){
$name = $_POST['name'];
$email = $_POST['email'];
$tel = $_POST['tel'];
$arrive = strtotime($_POST['arrive']);
$depart = (strtotime($_POST['depart'])) - 86400;
?>
<p>You have chosen the following dates: </p>
<a name="booking-form"></a>
<?php
for ( $i = $arrive; $i <= $depart; $i = $i + 86400 ) {
echo $bookedDates = date('Y-m-d', $i );
if (in_array($bookedDates, $alreadyBooked)){
$bookdedDatesNice = date('D, j M Y', strtotime($bookedDates));
echo 'This date is not available : '.$bookdedDatesNice.'<br />';
} else {
echo 'Your dates are available';
$sqlinsert = "INSERT INTO bookings (name, email, tel, roomid, date) values ";
// Loop between timestamps, 24 hours at a time
for ( $i = $arrive; $i <= $depart; $i = $i + 86400 ) {
$bookedDates =date('Y-m-d', $i );
// Constructing the insert query
$sqlinsert .= " ('$name', '$email', '$tel', '$roomId', '$bookedDates'),";
}
$bulk_insert_query = rtrim($sqlinsert, ","); // to remove last comma
$resultinsert = $conn->query($bulk_insert_query);
?>
<p>Your booking has been received for: <br />
Please wait for a confirmation email on: <?php echo $email; ?>
</p>
<?php
// header('refresh:3; url=book.php?id='.$id.'#booking-form');
}// if
} // for
}
It is not working because in_array stops the duplicate values from being inserted into the database, but allows the others that aren’t duplicate to go through. What I need is that nothing is inserted into the database if any duplicates are found. And all are sent if no duplicates are found. I hope that makes sense and that this is possible and that someone can assist.