我试图让make $ row variable = $ time
$time = strtotime('" . $row['time']. "');
但它不会起作用。
以下是整个代码:
<?php
$servername = "localhost";
$username = "u";
$password = "d1";
$dbname = "u59";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
<?php
if (empty($_GET)) {
header("Location:http://bithumor.co");
}
if(isset($_GET['id'])) {
$sql = "SELECT id, post_title, username, content_url, pro_pic, username FROM posts WHERE id = ".$_GET['id'];
$result = $conn->query($sql);
$time = strtotime('" . $row['time']. "');
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<div class='entire_post'><div class='menu'><center><img class='pro_pic' src=http://cdn.bithumor.co/pro_pics/" . $row['pro_pic']. "><title>" . $row['post_title']. " </title><br><font face='HelveticaNeue-Light' font size='4'><div class='username'>" . $row['username']. "</div></center></font></div><center><br><br><br><img class='upload' src=http://cdn.bithumor.co/uploads/" . $row["content_url"]. " width='100%'></center> " . $row["id"]. "<br><br><br><br></div><div class='footer'><center><font face='HelveticaNeue-Light' font color='white' font size='4'>Posted ".humanTiming($time)." ago</center></font></div>";
}
$conn->close();
}
}
?>
<?php
function humanTiming ($time)
{
$time = time() - $time; // to get the time since that moment
$tokens = array (
31536000 => 'year',
2592000 => 'month',
604800 => 'week',
86400 => 'day',
3600 => 'hour',
60 => 'minute',
1 => 'second'
);
foreach ($tokens as $unit => $text) {
if ($time < $unit) continue;
$numberOfUnits = floor($time / $unit);
return $numberOfUnits.' '.$text.(($numberOfUnits>1)?'s':'');
}
}
?>
代码的重点是&#34; row [time]&#34;将等于帖子发布时间的$ time。然后时间将从代码中回显
Posted ".humanTiming($time)." ago
如何解决问题?
答案 0 :(得分:1)
您的代码中有多处错误。
在此行中使用字符串分隔符是错误的。
$ time = strtotime('“。$ row ['time']。”');
您希望将变量传递给strtotime()函数不变,这是正确的行:
$time = strtotime($row['time']);
在循环SQL查询结果之前,您正在使用此行,这意味着尚未定义$ row。此行属于while循环,但此外,您还需要再执行一步以保存结果,并且在使用之前不要覆盖它。你可能想要更像这样:
$ row ['timestamp'] = strtotime('“。$ row ['time']。”');
您不在SQL中查询名为“time”的列,因此即使您将正确的代码放在正确的位置,您仍然无法从数据库中获得合理的时间读数。