2

I have this variable ($sql) in PHP:

$sql = "SELECT DATE_FORMAT(FROM_DAYS(DATEDIFF(CURRENT_DATE, dob)),'%y Years %m Months %d Days') AS age WHERE id=$row[id]";

How to output the produced data as a PHP variable?

The query is taking the date of birth from my table and calculating the age from today's date.

How to echo the age in PHP?

1
  • 1
    link this should help you out Commented Jan 19, 2017 at 7:54

3 Answers 3

4

Just try this:

$con = mysqli_connect("localhost","user","pass", "database_name"); //your connection
$sql = "SELECT DATE_FORMAT(FROM_DAYS(DATEDIFF(CURRENT_DATE, dob)),'%y Years %m Months %d Days') AS age FROM table_name WHERE id=".$row['id'];    
$query = mysqli_query($con, $sql);
$result = mysqli_fetch_assoc($query);
echo $result['age'];

Don't forget to replace table_name.

Sign up to request clarification or add additional context in comments.

1 Comment

Sorry misunderstand
0

try this code

i see your code you miss table name

$sql = "SELECT DATE_FORMAT(FROM_DAYS(DATEDIFF(CURRENT_DATE, dob)),'%y Years %m Months %d Days') AS age WHERE id=$row[id]";

 $result = mysql_query($sql);
    while($query_data = mysql_fetch_row($result))
    $age= $query_data[0];
    print $age;

2 Comments

You don't have a table name and FROM either? Also the PHP variable $row[id] is wrong.. should be " . $row['id']. mysql_ functions are not supported anymore
yups i also miss those thing which you mention
0

You can try as below:

$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

$sql = "SELECT DATE_FORMAT(FROM_DAYS(DATEDIFF(CURRENT_DATE, dob)),'%y Years %m Months %d Days') AS age WHERE id=$row[id]";

$result = $conn->query($sql);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
    echo "age: " . $row["age"]. "<br>";}
} 
else {
echo "No result!";
}

You can reference from http://www.w3schools.com

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.