Johanhs Johanhs - 6 months ago 63
SQL Question

Calculate average age of members (PHP)

I want to create the average age of my members.
I already managed to get an array of all the date of births and found an easy way to calculate a birthday. But I don't manage to combine it.

My 'date of birth' - array:

$results = array();

$dob_array = mysqli_query($conn, "SELECT dob_array FROM members");

while($row = mysqli_fetch_assoc($dob_array)){
$results[] = $row;

The calculation of the age:

$today = new DateTime();
$birthdate = new DateTime("1991-01-01");
$interval = $today->diff($birthdate);
echo $interval->format('%y years');

Calculation average of my age-array:

$average = array_sum($array) / count($array);


Might be done with direct sql (using TIMESTAMPDIFF() and AVG() functions):

SELECT AVG(TIMESTAMPDIFF(YEAR, `dob`, NOW())) as `average` FROM `member`;