显示最后反应的时间

时间:2018-04-04 11:46:28

标签: php html mysql

我希望在添加最新的'reactie'时显示。我认为有一个简单的PHP解决方案,但我并没有真正找到它。

enter image description here

正如您在数据库中看到的那样,在添加反应时也会设置时间戳。现在我想显示添加最后一个反应的时间。

2 个答案:

答案 0 :(得分:0)

你可以这样做:

select max(create_time)
from reacties;

如果你想要整行:

select r.*
from reacties r
order by create_time desc
limit 1;

答案 1 :(得分:0)

尝试使用此代码,它将完成工作。

您只需添加数据库凭据即可。

https://www.w3schools.com/php/php_mysql_select.asp

这是一个PHP函数,用于将时间戳转换为“前”格式,并将其与MySQLi Query结合使用。 Converting timestamp to time ago in PHP e.g 1 day ago, 2 days ago…

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

function time_elapsed_string($datetime, $full = false) {
    $now = new DateTime;
    $ago = new DateTime($datetime);
    $diff = $now->diff($ago);

    $diff->w = floor($diff->d / 7);
    $diff->d -= $diff->w * 7;

    $string = array(
        'y' => 'year',
        'm' => 'month',
        'w' => 'week',
        'd' => 'day',
        'h' => 'hour',
        'i' => 'minute',
        's' => 'second',
    );
    foreach ($string as $k => &$v) {
        if ($diff->$k) {
            $v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
        } else {
            unset($string[$k]);
        }
    }

    if (!$full) $string = array_slice($string, 0, 1);
    return $string ? implode(', ', $string) . ' ago' : 'just now';
}

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

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$sql = "SELECT reactie, create_time FROM reacties ORDER BY create_time DESC LIMIT 1";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo "Reactie: ".$row['reatie']." Timestamp: "+time_elapsed_string($row['create_time']);
    }
} else {
    echo "0 results";
}
$conn->close();
?>