我试图在源自MySQL表的数据上的insert_mysql.php中运行条件格式。数据源自Arduino Uno + WiFi Shield,每次按下按钮时都会发布一个值(任意值)和时间戳。 display_mysql.php输出到HTML,以便用户可以在网页上查看结果。出于此问题的目的,用户在页面上看到的唯一输出是按下按钮的最后日期/时间的单个时间戳,没有别的。我想根据以下内容格式化文本:
-css_1如果事件发生的时间少于两小时前。
-css_2是两个多小时前发生的事件。
我试过这个,但我怀疑有很多瑕疵。它只是一个开始的地方:
if ($result = mysql_query("SELECT MAX(TimeStamp) AS 'Last Time' FROM {$table}")< (%DateTime.Now% - 2)) {
echo '<div class="css_1">';
}
else{
echo '<div class="css_2">';
}
我继续收到与预期或意外字符相关的各种错误。此特定代码返回:&#34;解析错误:语法错误,意外&#39;%&#39;,期待&#39;)&#39;在...&#34;
我的问题是这样的......有没有办法在PHP中基于MySQL输出进行时间计算?如果事件属于两小时窗口,那么期望的结果是在绿色网页上打印日期和时间,这意味着它是一个新事件,如果它超过两个小时,则为红色,这意味着它是一个古老的事件。
答案 0 :(得分:0)
试试这个......
<?php
$host = 'localhost'; $db = 'db-name'; $user = 'db-user'; $pw = 'db-pwd';
$conn = new PDO('mysql:host='.$host.';dbname='.$db.';charset=utf8', $user, $pw);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try { // let's get our data from the database
$sql = "SELECT * FROM events";
$query = $conn->prepare($sql);
$query->execute();
$row = $query->fetch(PDO::FETCH_ASSOC);
$totalRows = $query->rowCount();
} catch (PDOException $e) {
die("Could not get the data: " . $e->getMessage());
}
$now = date('Y-m-d H:i:s', time()); // first we will get our current date & time
echo '<br>Time now: '.$now.'<br><br>';
$nowstring = strtotime($now); // convert that to a time string
do { // start looping through our data
$timestring = strtotime($row['eventdate']); // convert each of our dates to a time string
$diff = $nowstring - $timestring; // now substract the event date time string from the current date time string
$time = date('Y-m-d H:i:s', $timestring); // convert our event date time string back into a human readable date
echo 'Event Date: '.$time.'<br>'; // echo the event date to the page
if($diff > 7200) { // if the difference in time strings is greater than 7200, which is the number of seconds in 2 hours
echo '<div style="color:red">This is old</div><br><br>';
} elseif($diff < 0) { // if the difference in time strings is a negative number
echo '<div style="color:blue">This event hasn\'t occurred yet</div><br><br>';
} else { // otherwise the event date falls within the two our window
echo '<div style="color:#6c6">This is new</div><br><br>';
}
} while($row = $query->fetch(PDO::FETCH_ASSOC)); // end the loop
?>
数据库查询是用pdo_mysql编写的。然而,随意改变它;我建议坚持使用PDO或至少使用mysqli。
这是过程......
快乐的编码!