Update age column in database using php mysqli or pdo - php

How to update age automatically based on its DOB? I'm planning to write a script that fetch DOB column then calculate the age and update it. I started my idea but it still doesn't meet my objective.
Pls. help! Thanks in advance :)

Adding an age column when you have already date of birth, is slightly futile. Also, this means you would need to update the value once a year for every record, and at their birth date. That will start to get heavier and heavier. A lot of comments suggested to do the calculation of the age in PHP, this also would get heavy if you wanted to group people by age, you'd have to grab every records of the database and calculate their age. My suggestion is to use MySQL to calculate it, so you can use it in joins, where clauses, group bys and so on...
SELECT YEAR(NOW()) - YEAR(birthdate) - (DATE_FORMAT(NOW(), '%m%d') < DATE_FORMAT(birthdate, '%m%d')) as age FROM table
For more details, this was taken from How to get the difference in years from two different dates? which accounts for leap years.
You could easily create a MySQL function, call it calc_age or something and pass it the birthdate, that would return the current age and would be very easy to use...

Related

How to store age in SQL using PHP [duplicate]

How should I store Birthdate's in MySQL so that I can easily update everyone's Age on a daily basis via a Cron Job?
Does it even make sense to store the Age AND the Birthdate so that when searches involving the Age are made, I don't have to calculate each Age on-the-fly and waste CPU resources?
If so, how should I 1) store the Birthdate, and 2) calculate the Age each day?
I can imagine the daily cron script first filtering out the user's whose Birthdate month is not the current month, then filtering out the user's whose Birthdate day is not the current day, and then incrementing by one the age of each user that is left.
Does this make sense? If so, how would I do that? Is there a better way to do all of this?
The simple answer is don't; never store a persons age. It changes for each person yearly but, as you say, you have to check that it's correct for every person daily.
Only store the date of birth, and then calculate the age when selecting from the database. It's only today - date of birth so takes almost no CPUs at all.
EDIT:
To expand upon my comment in ManseUK's answer there's also the possibility of failure. What happens if your server / database is down? Or your update fails to run at its specified time? Or someone comes along and runs it manually after the update already been run for that date? Or someone turns off your scheduler? There's no danger of this happening if you calculate Age as you select from the database.
To select where age is between 25 and 30 years and assuming a DATE column dateofbirth your query would be something like:
select *
from users
where dateofbirth between date_add( curdate(), interval -30 year )
and date_add( curdate(), interval -25 year )
Ensure users is indexed on dateofbirth.
No, don't store age, just calculate it in your queries. As for the birthday, I prefer to have all my date/time in unix timestamps (because I hate to deal with portability across date-format-changing locale settings)
Does it even make sense to store the Age
No.
I don't have to calculate each Age on-the-fly and waste CPU resources?
As a matter of fact, you'd waste a zillion more "CPU resources" (of which you have too vague idea to be concerned of) with your everyday update approach.
Is there a better way to do all of this?
Store the birthdate and calculate the age at select time
what if you want to find out all the ones whose Age is greater than 25 but less than 30?
this is quite trivial query like this
WHERE birth_date BETWEEN date_sub(curdate(), INTERVAL 25 YEAR)
AND date_sub(curdate(), INTERVAL 30 YEAR)
the query would using an index (if any) and thus be blazing fast, without any [unnecessary] denormalizations
Im going to go against the majority all of the answers here.
I would store both ...
updating the age is quick and simple - a single mysql query could run every day and its done
calculating the age is time consuming when you have lots of page views - amount of times its viewed far outweighs the number of changes
Just imagine a table scenario - a table with 100 or 1000 rows that shows the age of a person ... how long is that going to take to compute ???
I always thought that Stackoverflow calculated the Reputation dynamically but you can see on the Stackoverflow data explorer that they dont - see the User object in the schema on the right. Its recorded and updated each time its changed - I would guess that this is purely because of the amount of times its viewed far outweighs the number of changes
I don't think it's totally true that computing age dynamically takes a lot of memory.
Why not create a table CALENDAR with 365 rows 1 row for each day of an year. And store a list of userid against the day corresponding to their birthday.
For each day just refer the table entry for that day and refresh the age of only those selected users.
This will reduce the complexity greatly even when the user base increases.

Proper MYSQL syntax for timestamp comparison and distinct results with certain exclusions

Sorry for asking, but I've never had to do such a complex MYSQL query before and I don't actually know what to google search in order to get the answer.
I have a poorly crafted database with a table of appointments of pregnant women that includes the day they came and the number of weeks pregnant they were at that time. I'm trying to select each one that should be 30 weeks right now but that doesn't already have a separate entry after 25 weeks pregnancy. I use the phone number to uniquely identify each person.
Since I really don't know how to formulate this query, this is the best I've come up with.
SELECT * FROM patientlist WHERE
UNIX_TIMESTAMP() - (UNIX_TIMESTAMP(`date`) - `weekspreg`*604800) > 29*604800
AND
UNIX_TIMESTAMP() - (UNIX_TIMESTAMP(`date`)- `weekspreg`*604800) <= 30*604800
AND
/* a subquery that keeps out results where the phone number would show up elsewhere in the table for a woman with more than 25 weeks of pregnancy. */
There has to be a better solution than separately querying each of the results from the date range by phone number to see if the weekspreg is more than 25.
Thank you in advance for any help or direction.
Your entire WHERE is incorrect. A query can only have ONE where clause. You join multiple conditions with and and or, not and where:
WHERE foo AND bar // correct
WHERE foo AND WHERE bar // syntax error
Check out the MySQL Date and Time Functions. For example, I'm not entirely certain what that last WHERE clause is trying to do, but I believe the first portion could be rewritten as something like:
SELECT *
FROM patientlist
WHERE `date` - interval `weekspreg` week
between now() - interval 29 week
and now() - interval 30 week

What would be the best way to store birthdate(birthday) field with optional year

I have mysql database, with birthdate column as date.
What would be the best way to save into this column, with optional year. Should I just put some random year on it? what is the best practice to save birthday in database.
I create 3 text field in cakephp, day, month, and year.. but not sure how to approach this, to save in database, since if I randomly put the year (maybe 0001, since 0000 is not accepted), when I pull it back, it will show the year.
Just an opinion, but if the year is optional (some will have it; some won't) I'd use a DATE type and set the year to zero. You can check for birthdays without years like this:
SELECT * FROM myTable WHERE YEAR(birthdate) = 0
Or if the birthdate column is indexed use this instead because it'll be optimizable:
SELECT * FROM myTable WHERE birthdate <= '0000-12-31'
If the year is forbidden for all values - in other words you'll never store the year - I'd recommend separate month and day columns.
Might it be best to use three columns, Day, Month, and Year, and treat Year as optional?
Edit: Although using two might be cleaner. one DATE column and just put a dummy year in (0000) and one YEAR column. Then assemble the two as you use them. That way you get all the formatting, sorting and data validation that the data types provide, but you can still ignore the year when you don't have it
The best approach is to have two fields:
birthdate which is a date
BirthdayHasYear which is a flag (such as a tinyint)
The reason for not depending on a rule like "when the year is zero then it is unknown" is that the data structure is very hard to understand -- in the future or if someone else looks at it. I would then be inclined to add a constraint that said "if BirthDayHasYear is true then the year on birthdate is 0 (or whatever).
Alternatively, I would have one field of birthdate and then only access the table through a view where such fields as:
BirthdayHasYear
Age
are defined as additional fields in the view. In other databases, I would use this approach with computed columns.

How to store Birthdate and Age so that Age can be updated daily in PHP/MySQL?

How should I store Birthdate's in MySQL so that I can easily update everyone's Age on a daily basis via a Cron Job?
Does it even make sense to store the Age AND the Birthdate so that when searches involving the Age are made, I don't have to calculate each Age on-the-fly and waste CPU resources?
If so, how should I 1) store the Birthdate, and 2) calculate the Age each day?
I can imagine the daily cron script first filtering out the user's whose Birthdate month is not the current month, then filtering out the user's whose Birthdate day is not the current day, and then incrementing by one the age of each user that is left.
Does this make sense? If so, how would I do that? Is there a better way to do all of this?
The simple answer is don't; never store a persons age. It changes for each person yearly but, as you say, you have to check that it's correct for every person daily.
Only store the date of birth, and then calculate the age when selecting from the database. It's only today - date of birth so takes almost no CPUs at all.
EDIT:
To expand upon my comment in ManseUK's answer there's also the possibility of failure. What happens if your server / database is down? Or your update fails to run at its specified time? Or someone comes along and runs it manually after the update already been run for that date? Or someone turns off your scheduler? There's no danger of this happening if you calculate Age as you select from the database.
To select where age is between 25 and 30 years and assuming a DATE column dateofbirth your query would be something like:
select *
from users
where dateofbirth between date_add( curdate(), interval -30 year )
and date_add( curdate(), interval -25 year )
Ensure users is indexed on dateofbirth.
No, don't store age, just calculate it in your queries. As for the birthday, I prefer to have all my date/time in unix timestamps (because I hate to deal with portability across date-format-changing locale settings)
Does it even make sense to store the Age
No.
I don't have to calculate each Age on-the-fly and waste CPU resources?
As a matter of fact, you'd waste a zillion more "CPU resources" (of which you have too vague idea to be concerned of) with your everyday update approach.
Is there a better way to do all of this?
Store the birthdate and calculate the age at select time
what if you want to find out all the ones whose Age is greater than 25 but less than 30?
this is quite trivial query like this
WHERE birth_date BETWEEN date_sub(curdate(), INTERVAL 25 YEAR)
AND date_sub(curdate(), INTERVAL 30 YEAR)
the query would using an index (if any) and thus be blazing fast, without any [unnecessary] denormalizations
Im going to go against the majority all of the answers here.
I would store both ...
updating the age is quick and simple - a single mysql query could run every day and its done
calculating the age is time consuming when you have lots of page views - amount of times its viewed far outweighs the number of changes
Just imagine a table scenario - a table with 100 or 1000 rows that shows the age of a person ... how long is that going to take to compute ???
I always thought that Stackoverflow calculated the Reputation dynamically but you can see on the Stackoverflow data explorer that they dont - see the User object in the schema on the right. Its recorded and updated each time its changed - I would guess that this is purely because of the amount of times its viewed far outweighs the number of changes
I don't think it's totally true that computing age dynamically takes a lot of memory.
Why not create a table CALENDAR with 365 rows 1 row for each day of an year. And store a list of userid against the day corresponding to their birthday.
For each day just refer the table entry for that day and refresh the age of only those selected users.
This will reduce the complexity greatly even when the user base increases.

DOB Collection from PHP to PHPMYADMIN

I have never collected DOB before. This is the first time i am doing it.
What is the best way to first of all collect dob from the php form?
Do i allow them to enter it as 12/03/1979 or something like 12031979.
And do i need 3 fields in the db like month, day, and year?
And then for the db, what do i select for the type, date? I want to be able to reuse this data for research purposes later.
Thanks a bunch!
Do you mean Date of Birth?
You will use DATE as datatype.
For the GUI, I suggest using three dropdown boxes: Year, Month and Day. Use 4 digits for years and month names (rather than numbers) to make it crystal clear.
Under no circumstances let the user enter a date in a text field, because you won't be able to parse it correctly afterwards.

Categories