2015-10-12 144 views
2

我希望能夠自己的年齡後,搜索用戶:年齡後搜索用戶。如何計算正確的年齡?

(Age input saved in variables $a1 - $a2) 
Age: □ - □ 
    -Search button- 

如果我選擇年齡:20-50我想20-50歲之間的所有用戶舊上市。 如果我選擇Age:x-30,我希望所有30歲以上的用戶都可以上市。

在分貝我用這種格式保存用戶的生日:2013-03-03。

要計算用戶的年齡和echo開我做這個網頁的年齡:

<?php 

$ag=$row['age']; 
$diff=time()-strtotime($ag); 
$age=date('Y-m-d', strtotime($ag)); 

echo floor($diff/60/60/24/365.25); 
?> 

如何使一個選擇查詢,其中年齡> $ A1和< $ A2?

回答

1

而不是從返回的日期計算年齡,你應該從期望的年齡

$mindate = is_numeric($a2)? date("Y-m-d", strtotime('-$a2 year')) : null; 
$maxdate = is_numeric($a1)? date("Y-m-d", strtotime('-$a1 year')) : null; 
$query = "SELECT * FROM whatevertable WHERE "; 
if(!is_null($mindate)) 
    $query .= "datecolumn > '$mindate'"; 
if(!is_null($maxdate)){ 
    if(!is_null($mindate) 
     $query .= " AND "; 
    $query .= "datecolumn < $maxdate"; 
} 

驗證和查詢拋光留作練習計算日期。

+0

我得到解析錯誤:語法錯誤,意外的'$ query'在 $ query。=「AND」; 和 $ query。=「'$ age'<$ maxdate」; – anon

+0

$ mindate = is_numeric($ a2)? date(「Y-m-d」,strtotime(' - $ a2 year')):null; $ maxdate = is_numeric($ a1)? date(「Y-m-d」,strtotime(' - $ a1 year')):null; $ query = mysqli_query($ con,「SELECT * FROM users WHERE c ='$ c'」); $ row = mysqli_fetch_array($ query); $ age = $ row ['age']; if(!is_null($ mindate)) $ query。=「'$ age'>'$ mindate'」; 如果{ 如果(is_null($ MINDATE) $查詢= 「和」!。 $查詢= 「 '$時代'<$的maxDate」。 }(is_null($的maxDate)!) – anon

+0

@anon我定義$查詢爲字符串,您將其定義爲mysqly_query的結果... – Ilario