2015-12-01 87 views
-1

我想用this年齡計算器來計算用戶的年齡,這是存儲在MySQL數據庫。我認爲這會起作用,但似乎並不如此。年齡計算採取從MySQL數據庫

我的問題是,我不知道如何從MySQL的用戶表中獲取日期。

<?php 
require_once 'core/init.php'; 

$user = new User(); 

if(!$user->isLoggedIn()) { 
    Redirect::to('index.php'); 
} 

    //date in mm/dd/yyyy format; or it can be in other formats as well 
    $birthDate = "<?php escape($user->data()->birthday); ?>";  //"08/13/2000"; 
    //explode the date to get month, day and year 
    $birthDate = explode("/", $birthDate); 
    //get age from date or birthdate 
    $age = (date("md", date("U", mktime(0, 0, 0, $birthDate[0], $birthDate[1], $birthDate[2]))) > date("md") 
    ? ((date("Y") - $birthDate[2]) - 1) 
    : (date("Y") - $birthDate[2])); 
    echo "Age is: " . $age; 
?> 
+0

什麼不適合你? – drmonkeyninja

+0

從MySQL用戶表獲取日期。 –

+0

更改'「<?php轉義($ user-> data() - > birthday);?>''轉義'($ user-> data() - > birthday);'。沒有必要把它放在一個字符串中,我很確定這是行不通的。 –

回答

1

我只是寫一個使用DateTime類和關聯方法這個簡單的類 - 應該很容易適應您的日期字符串是正確的格式。

class userage{ 

     private $dob; 
     private $options; 

     public function __construct($dob=false, $options=array()){ 
      $this->dob=$dob; 
      $this->options=(object)array_merge(array(
       'timezone' => 'Europe/London', 
       'format' => 'Y-m-d H:i:s' 
      ),$options); 
     } 

     public function calculate(){ 
      $opts=$this->options; 
      $timezone=new DateTimeZone($opts->timezone); 
      $dob=new DateTime(date($opts->format, strtotime($this->dob)), $timezone); 
      $now=new DateTime(date($opts->format, strtotime('now')), $timezone); 
      $age = $now->diff($dob); 

      $result=(object)array(
       'years'  => $age->format('%y'), 
       'months' => $age->format('%m'), 
       'days'  => $age->format('%d'), 
       'hours'  => $age->format('%h'), 
       'mins'  => $age->format('%i'), 
       'secs'  => $age->format('%s') 
      ); 
      $dob=$now=$age=null; 
      return $result; 
     } 
    } 

    $ua=new userage('1970-09-05'); 
    $age=$ua->calculate(); 

    echo '<pre>',print_r($age,true),'</pre>'; 

/* 
    outputs 
    ------- 
    stdClass Object 
    (
     [years] => 45 
     [months] => 2 
     [days] => 26 
     [hours] => 8 
     [mins] => 53 
     [secs] => 30 
    ) 

*/ 
+0

這並不能解決我的問題。腳本本身工作得很好,我唯一的問題是從MySQL用戶表中獲取日期。 –

+0

我在3分鐘前看到,您添加的問題本身只是從數據庫獲取數據。這應該是一個相當簡單的SQL查詢 – RamRaider