I have made a simple chat system. I want only to pull the last two ours of messages from the database instead of the complete database. Can someone show me how this can be done? Thanks!
Code:
if (isset($_SESSION['id'])) {
$userId = $_SESSION['id'];
$username = $_SESSION['username'];
$userLabel = $_SESSION['nickname'];
}
$connect = mysqli_connect("", "", "", "root");
mysqli_select_db($connect, "root");
$result1 = mysqli_query($connect, "SELECT * FROM chat ORDER by id DESC");
while ($extract = mysqli_fetch_assoc($result1)) {
if ($extract['name'] == 'admin1') {
$color = '#D00003';
}
else if ($extract['name'] == 'admin2') {
$color = '#7E0002';
}
else {
$color = '#FFFFFF';
}
if ($extract['name'] == $userLabel) {
echo "
<div class='usermessage'>
<div class='mheader'>
<h2 style='color:".$color."'>" . $extract['time'] . "</h2>
<h3 style='color:".$color."'>" . $extract['name'] . "</h3>
</div>
<p>" . $extract['message'] . "</p>
</div>";
}
else {
echo "
<div class='message'>
<div class='mheader'>
<h2 style='color:".$color."'>" . $extract['time'] . "</h2>
<h3 style='color:".$color."'>" . $extract['name'] . "</h3>
</div>
<p>" . $extract['message'] . "</p>
</div>";
}
}
?>
答案 0 :(得分:2)
You should use SQL date_sub
like that:
SELECT *
FROM `chat`
WHERE `time` >= DATE_SUB(NOW(), INTERVAL 2 HOUR)
ORDER by `id` DESC
答案 1 :(得分:1)
One way to do this...
SELECT * FROM chat
where
DATE_SUB(CURDATE(),INTERVAL 120 MINUTE) <= date_col;
ORDER by id DESC
Check out official documentation for more information http://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html