检查输入的开始和结束日期是否在数据库中已经开始和结束日期之间

时间:2015-08-12 22:10:37

标签: php mysql validation date datetime

我正在预订脚本租车。用户将在预订时,开始日期和结束日期输入两个日期,我需要它检查输入的日期是否已经存储在特定汽车的Db中的日期之间, 简单来说,如果从2015-23-08到2015-25-08预订了汽车,并且用户输入了这两个之间的日期,则显示其他明智的错误。

代码问题:即使我输入了不同的值,它也始终显示“介于两者之间”

代码:

include 'connection.php';
if (isset($_GET['id'])) {
// escape variables for security
$fleettype = $_POST['fleettype'];
$fleetname = $_POST['fleetname'];
$fleetclass = $_POST['fleetclass'];
$fleetdescription = $_POST['fleetdescription'];
$fleetprice = $_POST['fleetprice'];
$username = $_POST['username'];
$useremail = $_POST['useremail'];
$userphone = $_POST['userphone'];
$sdate = $_POST['sdate'];
$edate = $_POST['edate'];
$time = $_POST['time'];
$driver = $_POST['driver'];
$useremail = $_POST['useremail'];
$id = preg_replace('#[^0-9]#i', '', $_GET['id']);
$products = mysqli_query($con, "SELECT * FROM fleet WHERE id='$id' LIMIT 1 ");
while ($row = mysqli_fetch_assoc($products))
{ 

         $stime = $row["stime"];
         $etime = $row["etime"];
         }


$entereddate = DateTime::createFromFormat('Y/m/d', $stime);
$contractDateBegin = DateTime::createFromFormat('Y/m/d', $sdate);
$contractDateEnd = DateTime::createFromFormat('Y/m/d', $edate);


if ($entereddate >= $contractDateBegin && $entereddate <= $contractDateEnd)
{
 echo "in between";
}

else {
  echo "no";
}

}   

2 个答案:

答案 0 :(得分:3)

如果日期对变量有帮助,则不需要将日期用单引号括起来,所以更改你的`createFromFormat语句就好了。

另外,其他人必须有一个echo "no",您只有"no"

$entereddate       = DateTime::createFromFormat('Y/m/d', $stime);
$contractDateBegin = DateTime::createFromFormat('Y/m/d', $sdate);
$contractDateEnd   = DateTime::createFromFormat('Y/m/d', $edate);

if ($entereddate >= $contractDateBegin && 
    $entereddate <= $contractDateEnd)
{
    echo "in between";
} else {
    echo "no";
}

你可能会得到更好的结果,因为我很确定你无法比较那样的DateTime对象。

$entereddate       = strtotime($stime);
$contractDateBegin = strtotime($sdate);
$contractDateEnd   = strtotime($edate);


if ($entereddate >= $contractDateBegin &&
    $entereddate <= $contractDateEnd)
{
    echo "in between";
} else {
    echo "no";
}

答案 1 :(得分:2)

您不能在变量周围放置单引号,也不能插入它们:

$entereddate = DateTime::createFromFormat('Y/m/d', '$stime');
$contractDateBegin = DateTime::createFromFormat('Y/m/d', '$sdate');
$contractDateEnd = DateTime::createFromFormat('Y/m/d', '$edate');

应该是:

$entereddate = DateTime::createFromFormat('Y/m/d', $stime);
$contractDateBegin = DateTime::createFromFormat('Y/m/d', $sdate);
$contractDateEnd = DateTime::createFromFormat('Y/m/d', $edate);

发生的事情是,您输入的“日期”都没有效 - 它会查看字符串$stime - 可能就像字符串banana一样,是一个日期。它不是。因此$entereddate设置为false。与$contractDateBegin$contractDateEnd一样。

那么,它会检查false >= false && false <= false是否为false == falseecho "in between";。所以它始终是@Column

http://sandbox.onlinephpfunctions.com/code/0cb5b5fc82598708fdff66d013d041467bb6fd8a