【发布时间】:2012-09-30 05:33:29
【问题描述】:
我正在尝试从类函数中设置会话变量的值,并稍后在同一类的不同函数中比较该会话值。 __construct() 函数中没有这些函数。
问题似乎是比较永远不会返回 true。
<?php
session_start();
$class = new Class();
?>
blah blah blah
<script type="text/javascript">
// Ajax function to call PHP that creates new Class isntance and executes a Class->function();
setInterval('checkNew()', 10000);
</script>
blah blah blah
// Another Ajax Function that calls creates a new Class isntance and executes the initial Class->function();
<body onload="getMessages();">
blah blah blah
下一个函数摘录是从<body onload=""> ajax 调用的脚本中运行的。
这是为了稍后在不同的函数中比较这个$_SESSION['last_sms']。
// Check the now() stamp of the most recent message loaded
$recent_msg_query = "SELECT date_received FROM messages ORDER BY date_received DESC LIMIT 1";
$recent_statement = $this->db_handle->prepare($recent_msg_query);
$recent_statement->execute();
$most_recent = $recent_statement->fetch(PDO::FETCH_NUM);
$_SESSION['last_sms'] = $most_recent[0];
这是应该进行比较的类中的函数,每十秒一次(通过setInterval('checkNew()', 10000);)
public function checkNew()
{
// Check the now() stamp of the most recent message loaded and compares it
// to a stored now() stamp.
$recent_msg_query = "SELECT date_received FROM messages ORDER BY date_received DESC LIMIT 1";
$recent_statement = $this->db_handle->prepare($recent_msg_query);
$recent_statement->execute();
$most_recent = $recent_statement->fetch(PDO::FETCH_NUM);
if (!isset($_SESSION['last_sms'])) {
$_SESSION['last_sms'] = $most_recent[0];
}
if ($_SESSION['last_sms'] !== $most_recent[0]) {
echo "New message(s) available, refresh.";
} else {
echo "No new messages yet.";
}
}
当我发送新消息时,页面仍然显示“还没有新消息”。你们能帮我弄清楚我在哪里偏离了这条路吗?这个$_SESSION stuff 是目前唯一不起作用的东西。
【问题讨论】:
-
在
checkNew()函数中运行var_dump($_SESSION['last_sms'])以查看是否已设置 -
在 AJAX 处理程序脚本中是否调用了
session_start()also? (无论getMessages()回电) -
@jdstankosky 你的问题。
session_start()不仅仅是一个会话初始化器。必须在访问会话的任何 PHP 脚本上调用它。 -
@MichaelBerkowski 啊,这确实解决了问题。谢谢。
-
@jdstankosky 我会把它作为答案放在下面。