简体   繁体   English

如何使用PHP和MySQL从出生日期获取年龄?

[英]How to get the age from a birthdate using PHP & MySQL?

I ask my users for their birthdate and store it in my database in the following way $month $day $year output May 6 1901 but I was wondering how can I get the age from the stored birthdate using PHP & MySQL? 我向用户询问他们的生日,并以如下方式将其存储在数据库中$month $day $year May 6 1901 $year May 6 1901但是我想知道如何使用PHP和MySQL从存储的生日中获得年龄吗?

Here is the PHP code. 这是PHP代码。

if (isset($_POST['submitted'])) {

$mysqli = mysqli_connect("localhost", "root", "", "sitename");
$dbc = mysqli_query($mysqli,"SELECT users.*
                             FROM users 
                             WHERE user_id=3");

$month_options = array("Month", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");

$day_options = array("Day", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31");

$month = mysqli_real_escape_string($mysqli, htmlentities(strip_tags($_POST['month'])));
$day = mysqli_real_escape_string($mysqli, htmlentities(strip_tags($_POST['day'])));
$year = mysqli_real_escape_string($mysqli, htmlentities(strip_tags($_POST['year'])));


    if (mysqli_num_rows($dbc) == 0) {
            $mysqli = mysqli_connect("localhost", "root", "", "sitename");
            $dbc = mysqli_query($mysqli,"INSERT INTO users (user_id, month, day, year) 
                                         VALUES ('$user_id', '$month', '$day', '$year')");
    }


    if ($dbc == TRUE) {
            $dbc = mysqli_query($mysqli,"UPDATE users 
                                         SET month = '$month', day = '$day', year = '$year'
                                         WHERE user_id = '$user_id'");

            echo '<p class="changes-saved">Your changes have been saved!</p>';

    }


    if (!$dbc) {
            print mysqli_error($mysqli);
            return;
    }
}

Here is the html. 这是HTML。

<form method="post" action="index.php">
    <fieldset>
        <ul>
            <li><label>Date of Birth: </label>
            <label for="month" class="hide">Month: </label>
            <?php // month options

            echo '<select name="month" id="month">' . "\n";
              foreach($month_options as $option) {
                if ($option == $month) {
                  echo '<option value="' . stripslashes(htmlentities(strip_tags($option))) . '" selected="selected">' . stripslashes(htmlentities(strip_tags($option))) . '</option>' . "\n";
                } else {
                  echo '<option value="'. stripslashes(htmlentities(strip_tags($option))) . '">' . stripslashes(htmlentities(strip_tags($option))) . '</option>'."\n";
                }
              }
            echo '</select>';

            ?>
            <label for="day" class="hide">Day: </label>
            <?php // day options

            echo '<select id="day" name="day">' . "\n";
              foreach($day_options as $option) {
                if ($option == $day) {
                  echo '<option value="' . stripslashes(htmlentities(strip_tags($option))) . '" selected="selected">' . stripslashes(htmlentities(strip_tags($option))) . '</option>' . "\n";
                } else {
                  echo '<option value="'. stripslashes(htmlentities(strip_tags($option))) . '">' . stripslashes(htmlentities(strip_tags($option))) . '</option>'."\n";
                }
              }
            echo '</select>';

            ?>              
            <label for="year" class="hide">Year: </label><input type="text" name="year" id="year" size="4" maxlength="4" value="<?php if (isset($_POST['year'])) { echo  stripslashes(htmlentities(strip_tags($_POST['year']))); } else if(!empty($year)) { echo  stripslashes(htmlentities(strip_tags($year))); } ?>" /></li>


            <li><input type="submit" name="submit" value="Save Changes" class="save-button" />
                <input type="hidden" name="submitted" value="true" />
            <input type="submit" name="submit" value="Preview Changes" class="preview-changes-button" /></li>
            </ul>
    </fieldset>

</form>

If you just need to calculate age from a given date, there are lots of answers to this that have already been posted. 如果您只需要计算给定日期的年龄,则已经发布了许多答案。 See this one: Calculate years from date 看到这一点: 计算日期之后的年份

Create function in php : 在php中创建函数:

function calculateage($BirthDate)
{
list($Day, $Month, $Year) = explode(".", $BirthDate);

$YearDiff = date("Y") - $Year;

if(date("m") < $Month || (date("m") == $Month && date("d") < $DayDiff))
{
$YearDiff--;
}
return $YearDiff;
}

call function where age shown like 显示年龄的通话功能

calculateage($date)

Where $date is birthdate in mysql table 其中$date是mysql表中的birthdate

With datetime:createfromformat you could parse the date into a DateTime object and do you calculations on the object which makes it quite easy. 使用datetime:createfromformat,您可以将日期解析为DateTime对象,并对该对象进行计算,这非常容易。 Requires php 5.3 though. 需要php 5.3。

function getAge($then) {
    $then = date('Ymd', strtotime($then));
    $diff = date('Ymd') - $then;
    return substr($diff, 0, -4);
}

From JYelton's answer, just put this function in your code, and send your date to it: 根据JYelton的回答,只需将此函数放入代码中,然后将日期发送给它:

$age = getAge('June 30 1959');

echo $age;

Try this: 尝试这个:

$age = floor((time() - mktime(0,0,0,$month,$day,$year))/31536000);

It takes the time now, subtracts the time of their birth, converts it to years and floors it giving you their current age. 现在需要时间,减去他们的出生时间,将其转换为年数和底限,从而可以得出他们的当前年龄。

you can try this :: 你可以试试这个::

if( isset($_POST['submit']) )   
{
   $day = $_POST['day'];
   $month = $_POST['month'];
   $year = $_POST['year'];

   $cal_date = mktime(0, 0, 0, $month, $day, $year );  // convert in second
   $start_date = date('Y-m-d',$cal_date);   // make real time as  Year-month-day for store value in database

   $birthDay = strtotime("now") - strtotime($start_date);

   echo substr($birthDay, 0, -4);


  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM