我想阻止用戶輸入已經採取的日期和數據庫內。就像他們輸入日期類似於數據庫中的日期一樣,他們會收到一條警告,提示「您選擇的日期已經被使用」。我有這樣的代碼,但它沒有這樣做,陷阱在php採取的日期
DATABASE
CREATE TABLE `date_tbl` (
`date_id` int(11) NOT NULL,
`date` date NOT NULL,
`time` text NOT NULL,
`ordertype` int(10) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
PHP
<?php
include('db.php');
if(isset($_POST['reserve'])){
$fdate = $_POST['datepicker'];
$ftime = $_POST['time'];
$fdate_array = array();
$ftime_array = array();
$q=$conn->query("SELECT * FROM date_tbl");
while($row=mysqli_fetch_array($q)){
$fdate_array[]=$row['date'];
$ftime_array[]=$row['time'];
}
if(array_intersect($fdate_array, $ftime_array)){
die ("<script>
alert('Date is not available! Please pick another date');
window.location.href='index.php';
</script>");
}else{
$insertDate=$conn->query("INSERT INTO date_tbl (date_id, date, time, ordertype, client_id) VALUES ('','$fdate','$ftime',0)");
if(!$insertDate){
die('error');
}else{
$setin = $conn->query('SET foreign_key_checks = 1');
die("<script>
alert('You have reserved a date.');
window.location.href='index.php';
</script>");
}
}
}
HTML
<div class="col-md-4">
<h5 style="font-family:Lucida Calligraphy">Date:</h5>
<input type="text" name="datepicker" class="form-control" placeholder='Select date' id="datepicker" style="margin-left: -15px" />
<script>
$(function() {
$('#datepicker').datepicker({
minDate: 0,
dateFormat: 'yy-mm-dd'
});
});
</script>
</div>
<div class="col-md-4">
<h5 style="font-family:Lucida Calligraphy">Time:</h5>
<select type="text" name="time" id="time" class="form-control">
<option>Select time</option>
<option>10:00 AM</option>
<option>1:00 PM</option>
</select>
</div>
什麼是'datepicker','time'和'date_tbl'相當於字段的格式? – Optimae
@Optimae我現在編輯它我也添加了我的數據庫。 –
您可以將'date_tbl'字段設置爲唯一,並捕獲與違反約束條件有關的任何插入錯誤。你所擁有的問題是,如果兩個請求在同一時間採用完全相同的日期,他們都可能成功。 – apokryfos