简体   繁体   中英

Output mysql query result in a php variable

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?

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.

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;

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

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