【问题标题】:How to store the age of the person using his DOB entered but it's not working如何存储使用他的出生日期的人的年龄输入但它不起作用
【发布时间】:2025-12-09 08:35:01
【问题描述】:

这里的 DOB 有输入文本字段的值

 $DOB = $_POST['DOB'];
 $today = date("d-m-Y");
 $diff = date_diff(date_create($DOB), date_create($today));
 echo 'Age is '.$diff->format('%y');
 $a = $diff->format('%y');
 $age = $_POST[$a];

这里是插入查询

 $sql="INSERT INTO details (`id`, `email`, `member_id`, `name`, `DOB`, `gender`, 'age')
       VALUES (NULL,'$email2', '$member_id', '$name', '$DOB',  '$gender', '$age')";
 $query=mysqli_query($con,$sql);

我认为这是静态的问题,我猜它需要使用输入文本值动态完成?如何获取输入文本值,以便存储在 DOB 字段中输入的出生日期的年龄?

【问题讨论】:

标签: javascript php sql datetime sql-insert


【解决方案1】:

我不建议将年龄存储在数据库中。这是一个派生信息,其值随时间而变化。存放后 1 年内将过时。

您可以使用简单的日期函数轻松地直接在查询中计算年龄,这些函数在大多数数据库中都可用(当然,假设您将dob 存储为合法的date 数据类型)。假设您正在运行 MySQL:

timestampdiff(year, dob, current_date) as age

如果你要经常输入这个,你可以考虑创建一个视图:

create view v_details as
select d.*, timestampdiff(year, dob, current_date) as age
from details d

【讨论】:

    最近更新 更多