Reputation: 33
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?
Upvotes: 2
Views: 4276
Reputation: 619
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
Upvotes: 0
Reputation: 570
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.
Upvotes: 4
Reputation: 298
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;
Upvotes: 0