简体   繁体   English

如何检查两个日期之间是否存在条目

[英]how to check if an entry exists between two dates

I have an sql table "flights" where there are all the details of all the flights: aircraft registration, arrival date, departure date an so on... Now when I want to create a new flight I would like to check if a flight with the same registration already exists between two given dates. 我有一个SQL表“ flights”,其中包含所有航班的所有详细信息:飞机注册,到达日期,出发日期等等...现在,当我想创建一个新航班时,我想检查一下航班在两个给定日期之间已经存在具有相同注册的注册。 EG: have a flight called IFLY arriving 22/7/2019 and departing 25/7/2019, now if I try to create another flight with the same registration but arriving 23/7/2019 and departing 24/7/2019, I would like to check in the database that during those dates another flight with the same registration is already in the database and alerting the user. EG:有一个名为IFLY的航班,它将在22/7/2019到达并离开25/7/2019,现在,如果我尝试创建一个具有相同注册但又在23/7/2019到达并离开24/7/2019的航班,我会想要在数据库中检查在这些日期期间数据库中已经存在另一个具有相同注册的航班,并提醒用户。

I have tried something like this: html form via jquery/ajax calling a request on the DB 我已经尝试过这样的事情:通过jquery / ajax的html表单在数据库上调用请求

$regist = $_POST['regCreate'];
$arrivalDate = $_POST['adof'];
$departureDate =$_POST['ddof'];

$sql = "SELECT reg FROM flights WHERE reg = '$regist' AND (adof or ddof) 
 >= '$arrivalDate' AND (adof or ddof) <= '$departureDate'  ";//
$data = mysqli_query($conn, $sql);

 if (mysqli_num_rows($data) > 0) {
  echo 'exists';
 }

this code is not working bacause if I create a new flight that is situated between two dates already created is not giving me the excepted result. 如果我创建的新航班位于已创建的两个日期之间,则此代码不起作用,原因是没有给我例外结果。

Two time periods overlap if they each begin before the other ends. 如果两个时间段都在另一个结束之前开始,则两个时间段重叠。

You can phrase this as: 您可以将其表达为:

SELECT f.reg
FROM flights f
WHERE f.reg = ? and
      f.departureDate < ? and  -- the input arrival date
      f.arrivalDate > ?        -- the input departure date

Note that I changed the syntax to use parameters. 请注意,我更改了语法以使用参数。 This is a best practice when devising queries in PHP or any other application layer. 在PHP或任何其他应用程序层中设计查询时,这是最佳实践。

I have founded this solution 我已经建立了这个解决方案

$sql = "SELECT reg, adof, ddof FROM flights WHERE reg = '$regist' AND adof < 
'$arrivalDate' ";//
 $data = mysqli_query($conn, $sql);

if (mysqli_num_rows($data) > 0) {
 foreach ($data as $key => $v) {
  if ($v['ddof'] >= $arrivalDate) {
   echo 'exists';
   }
  }
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM