dougong7850
dougong7850
2018-01-02 17:06

MySQL数据库和导入日期问题

已采纳

Okay,so in my mysql database I use a date field. Using PHP I check if the user is 18 years of age or not. Then I try to enter all the form information to my MySQL database to make a user. I keep getting a blank screen (besides my navbar and footer) The user is not being saved into the database, and the error log shows this error: PHP Recoverable fatal error: Object of class DateTime could not be converted to string in ....

$age = checkAge($_POST["birthday"]);
if($age != false) 
{
  $ageSuc = "All Good!";
}
else ....


function checkAge ($data)
{
  $dateObj = new DateTime($data);
  $ageLimit = new DateTime('-18 years');
  if ($dateObj > $ageLimit)
  {
   return false;
  }
  else 
  {
    $dateObj->format('Y-m-d');
    return $dateObj;
  }
}

So the question is, do I need to convert the dateTime Obj into a string before MySQL will accept it? The field is set to hold 'dates' so I thought the date obj would be the same thing? How does one change it to a string.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • douzengjian1535 douzengjian1535 3年前

    You are returning the DateTime object, because the format function returns a string, it doesn't change the object. Try returning the result of the format function which is the formatted string.

    return $dateObj->format('Y-m-d');
    
    点赞 评论 复制链接分享
  • douyinzha5820 douyinzha5820 3年前
    $age = checkAge($_POST["birthday"]);
      if($age != false)
         {
           $ageSuc = "All Good!";
         }
      else ....
    
    
     function checkAge ($data)
        {
           $dateObj = new DateTime($data);
           $ageLimit = new DateTime('-18 years');
           if ($dateObj > $ageLimit)
             {
               return false;
              }
              else 
               {
                 return $dateObj->format('Y-m-d');
                }
          }
    

    If you want a string result, you have to return the format() result, not the object itself.

    But the error you have specified is not triggered directly in this code, but somewhere in the else, where you try to convert the result to string.

    点赞 评论 复制链接分享

相关推荐