我在这里看过很多帖子,但我仍然无法弄清楚这一点。
我正在尝试在注册我的网站之前验证某人是否超过13岁。这就是我到目前为止所拥有的
<?php
if (is_string($_POST['birthday']) && $_POST['birthday'] != 'mm/dd/yyyy')
{
$dateObj = new DateTime($_POST['birthday']);
$ageLimit = new DateTime('13 years');
$now = new DateTime(date("Y/m/d"));
$checkDate = $now->diff($ageLimit);;
if($checkDate > $dateObj)
{
$errors[]='You must be atleast 13 years old to join.';
}
else
{
$bday = mysqli_real_escape_string($db,$_POST['birthday']);
}
}
else
{
$errors[]= 'Enter your birthday.';
}
代码将始终运行到
$bday = mysqli_real_escape_string($db,$_POST['birthday']);}
无论在日期字段中输入什么,结果始终为1。
任何人都可以帮我吗?我不能自己想出这个。
<b>Birth Date</b><br><input type="date" name="birthday"
value=<?php if(isset($_POST['birthday']))echo $_POST['birthday'];?>><br>
答案 0 :(得分:1)
比较运算符与DateTime
一起使用,请参阅答案here。
所以这样的事情应该有用
$dateObj=new DateTime($_POST['birthday']);
$ageLimit=new DateTime('-13 years');
if($dateObj > $ageLimit){
//TOO YOUNG
}
每条评论的编辑
替换
if(isset($_POST['birthday']))echo $_POST['birthday'];
与
if(isset($_POST['birthday'])) {
echo $_POST['birthday'];
} else {
echo 'mm/dd/yyyy';
}
或更改
if (is_string($_POST['birthday']) && $_POST['birthday'] != 'mm/dd/yyyy')
要
if (!empty($_POST['birthday']) && is_string($_POST['birthday']))
答案 1 :(得分:1)
您有几个错误
DateTime()
DateTime()
$checkDate
是DateInterval
对象,无法与DateTime
对象相比您可以通过比较可比较的DateTime
对象来解决此问题并简化代码:
$birthday = new DateTime($_POST['birthday']);
$ageLimit = new DateTime('-13 years');
if ($birthday < $ageLimit) {
// they're old enough
}
else {
// too young
}
答案 2 :(得分:0)
使用strtotime计算日期差异可能更容易。年轻人的数字越高。因此,如果人的年龄高于最低年龄,他们就不够年长。
if(is_string($_POST['birthday'])&&$_POST['birthday']!='mm/dd/yyyy') {
$minAge = strtotime("-13 years");
$dateObject = strtotime($_POST['birthday']);
if($dateObject > $minAge) {
$errors[]= 'You must be atleast 13 years old to join.';
}
} else {
$errors[]='Enter your birthday.';
}