我目前正在将我的网站转换为PDO,但我遇到了一点障碍,我有一个功能,将日期时间转换为文本,说明它已经发布了多久,但在将我的查询更改为PDO后,该功能是给我一个错误:
错误:
Notice: Undefined variable: retval in C:\wamp\www\pdoconvert\threads.php on line 301 (line 20 of the function)
功能:
function time_ago($date,$granularity=2) {
$date = strtotime($date);
$difference = time() - $date;
$periods = array('decade' => 315360000,
'year' => 31536000,
'month' => 2628000,
'week' => 604800,
'day' => 86400,
'hour' => 3600,
'minute' => 60,
'second' => 1);
if ($difference < 5) { // less than 5 seconds ago, let's say "just now"
$retval = "Posted just now";
return $retval;
} else {
foreach ($periods as $key => $value) {
if ($difference >= $value) {
$time = floor($difference/$value);
$difference %= $value;
$retval .= ($retval ? ' ' : '').$time.' '; <-- Line 301
$retval .= (($time > 1) ? $key.'s' : $key);
$granularity--;
}
if ($granularity == '0') { break; }
}
return ' Posted: '.$retval.' ago';
}
}
查询:
$nostmt = $db->prepare ("SELECT threads.Thread_ID, threads.Thread_Title, threads.Board_ID, threads.Author, threads.Thread_Sticky, threads.Thread_Locked, Sub1.LatestPost, Sub1.PostCount, members.Post_As, members2.Member_ID AS LastPostMemberID, members2.Post_As AS LastPostMemberPostAs
FROM threads
INNER JOIN (SELECT Thread_ID, MAX(posts.Post_DateTime) AS LatestPost, COUNT(*) AS PostCount FROM posts GROUP BY Thread_ID) Sub1
ON threads.Thread_ID = Sub1.Thread_ID
INNER JOIN members
ON threads.Author = members.Member_ID
INNER JOIN posts posts2
ON posts2.Thread_ID = Sub1.Thread_ID AND posts2.Post_DateTime = Sub1.LatestPost
INNER JOIN members members2
ON members2.Member_ID = posts2.Member_ID
WHERE threads.Board_ID=:Board_ID
AND threads.Thread_Sticky='0'
ORDER BY Sub1.LatestPost DESC
LIMIT $offset, $rowsperpage");
$nostmt->bindValue( ":Board_ID", $Board_ID);
$nostmt->execute();
while($row = $nostmt->fetch(PDO::FETCH_ASSOC)) {
$Thread_ID = $row['Thread_ID'];
$Thread_Title = $row['Thread_Title'];
$Board_ID = $row['Board_ID'];
$Author = $row['Author'];
$Thread_Sticky = $row['Thread_Sticky'];
$Thread_Locked = $row['Thread_Locked'];
$Post_Author = $row['Post_As'];
$Posts = $row['PostCount'];
$Post_DateTime = time_ago($row['LatestPost']); <--time-ago function called
$Member_ID = $row['LastPostMemberID'];
$Post_As = $row['LastPostMemberPostAs'];
真正让我感到困惑的是我每输出一行得到两次这个错误,但我也得到了正确的超时输出。
我该如何解决这个问题?是我的伪劣PDO转换还是功能错误?
答案 0 :(得分:1)
您正在使用$retval
而未先将其初始化,这就是您收到通知的原因。尝试在函数顶部初始化它(例如,空字符串)。您还可以删除第301行上的连接点以达到相同的效果。
PHP中的通知不是错误。它们旨在警告您潜在的有害构造,如果您没有特意写下它们,可能会导致错误。可以在php.ini中禁用通知,默认情况下也是如此。 php.ini中的这行看起来像这样:
error_reporting = E_ALL & ~E_NOTICE
答案 1 :(得分:1)
您的$retval
变量未在此时定义(line 301
)。
解决这个问题:
$retval
$retval="";
变量
或
301
$retval=($retval ? ' ' : '').$time.' ';
我建议使用第一个选项