简体   繁体   中英

How to get the age from a birthdate using PDO & MySQL?

I don't know exactly how to put the code that is neccesary that show me the age with the birthdate that is in mysql ..always give me 1..can you please show me where is my error?

this is the code:

<?php
$query = "SELECT DATE_FORMAT(NOW(), '%Y') - DATE_FORMAT(f_nacimiento, '%Y') - (DATE_FORMAT(NOW(), '00-%m-%d') < DATE_FORMAT(f_nacimiento, '00-%m-%d')) AS age from PACIENTES where id_paciente = $_GET[id_paciente]";
echo print $age; ?>

in the db the row f_nacimiento is in date type (yyyy-mm-dd)

best regards!

The result is simply "1" because you are selecting a boolean expression.
That is, X < Y returns only 0 or 1.

There's a much easier way to do date arithmetic in MySQL. The DATEDIFF() function returns the number of days between two dates.

$query = "SELECT FLOOR(DATEDIFF(NOW(), f_nacimiento) / 365.25) AS age
    FROM PACIENTES
    WHERE id_paciente = ?";

if (($stmt = $pdo->prepare($query)) === false ) {
  die(print_r($pdo->errorInfo(), true));
}

$id_paciente = $_GET["id_paciente"];
if ($stmt->execute(array($id_paciente)) === false) {
  die(print_r($stmt->errorInfo(), true));
}

while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
  echo $row["age"] . "\n";
}

The table I tested this with is as follows:

CREATE TABLE `PACIENTES` (
  `id_paciente` int(11) NOT NULL AUTO_INCREMENT,
  `f_nacimiento` date DEFAULT NULL,
  PRIMARY KEY (`id_paciente`)
) ENGINE=InnoDB;

PS: The example code above shows two other important habits of PDO programming:

  • Use query parameters, do not interpolate strings directly into SQL.
  • Check for error status returned from prepare() and execute().

Re your comment, needing to display the age in years, months. Here's my second try (with days thrown in for fun):

SELECT TIMESTAMPDIFF(YEAR
   , f_nacimiento
   , NOW()
   ) AS Years,
   TIMESTAMPDIFF(MONTH
   , f_nacimiento
       + INTERVAL TIMESTAMPDIFF(YEAR, f_nacimiento, NOW()) YEAR
   , NOW()
   ) AS Months,
   TIMESTAMPDIFF(DAY
   , f_nacimiento
       + INTERVAL TIMESTAMPDIFF(MONTH, f_nacimiento, NOW()) MONTH
   , NOW()
   ) AS Days
FROM PACIENTES
WHERE id_paciente = 1;

use this query instead, and since you're using pdo use the prepared statements

SELECT EXTRACT(YEAR FROM NOW()) - EXTRACT(YEAR FROM f_nacimiento) age FROM pacientes WHERE id_paciente = ?

and for the php

$dbh = new PDO(.....
$st = $dbh->prepare($query);
$st->execute([(string)$_GET['id_paciente']]);
var_dump($st->fetchAll());

You need to use the $_GET variable correctly in a string.

$query = "SELECT DATE_FORMAT(NOW(), '%Y') - DATE_FORMAT(f_nacimiento, '%Y') - (DATE_FORMAT(NOW(), '00-%m-%d') < DATE_FORMAT(f_nacimiento, '00-%m-%d')) AS age from PACIENTES where id_paciente = $_GET[id_paciente]";

to:

$query = "SELECT DATE_FORMAT(NOW(), '%Y') - DATE_FORMAT(f_nacimiento, '%Y') - (DATE_FORMAT(NOW(), '00-%m-%d') < DATE_FORMAT(f_nacimiento, '00-%m-%d')) AS age from PACIENTES where id_paciente = \"" . $_GET['id_paciente'] . "\"";
// Do the query.... 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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