在php变量中输出mysql查询结果

时间:2017-01-19 07:45:09

标签: php sql

我在PHP中有这个变量($sql):

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

如何将生成的数据输出为 PHP变量

查询从我的表格中取出出生日期并计算从今天开始的年龄。

如何在PHP中回应年龄?

3 个答案:

答案 0 :(得分:3)

试试这个:

$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'];

不要忘记替换table_name。

答案 1 :(得分:0)

试试这段代码

我看到你错过了表名的代码

$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 :(得分:0)

您可以尝试如下:

$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!";
}

您可以参考http://www.w3schools.com