循环时,php变量不会在mysqli_stmt_fetch()内部递增

时间:2014-12-15 17:45:48

标签: php ajax while-loop

我正在构建一个通过Server-Sent Events更新的聊天应用程序。我的代码有问题,它试图增加搜索新消息的值:

include("../services/db_connect.php");
ini_set('max_execution_time', 0);
header("Content-Type: text/event-stream");
header("Cache-Control: no-cache");
$messages = array();
$lastMessageID=0;
$stmt="SELECT messageID FROM chat_messages ORDER BY messageID DESC LIMIT 1";
if($stmt = mysqli_prepare($db, $stmt)){
    mysqli_stmt_execute($stmt);
    mysqli_stmt_bind_result($stmt, $lastMessageID);
    mysqli_stmt_fetch($stmt);
}
mysqli_stmt_close($stmt);

while(true){
    $stmt2 = "SELECT chat_messages.messageID, chat_messages.userID, chat_messages.messageTime, chat_messages.messageText, chat_user.username FROM chat_messages, chat_user WHERE chat_messages.userID = chat_user.userID AND chat_messages.messageID > ? ORDER BY chat_messages.messageID ASC";
    $rows =0;
    if($stmt2 = mysqli_prepare($db, $stmt2)){
        mysqli_stmt_bind_param($stmt2, "i", $lastMessageID);
        mysqli_stmt_execute($stmt2);
        mysqli_stmt_bind_result($stmt2, $messageID, $userID, $messageTime, $messageText, $username);

        while(mysqli_stmt_fetch($stmt2)){
            array_push($messages, array(
                "mID" => $messageID,
                "userID" => $userID,
                "messageTime" =>$messageTime,
                "messageText" =>$messageText,
                "username" =>$username
            ));
            $lastMessageID++;
        }
    }
    echo("data:".json_encode($messages)."\n\n");
    @ob_flush(); @flush();
    sleep(4);
}    

在没有输入任何消息的情况下,脚本输出数据:[],但是当输入几条消息时,它将继续使用仅包含两个新变量的json字符串循环,这意味着$ lastMessageID变量不会更新。任何人都可以解释脚本有什么问题吗?

1 个答案:

答案 0 :(得分:0)

$ messages数组应该在while循环内初始化。这样,发送到客户端的数组只有新的mysql结果集,而不是以前存储的行。简单的编程原则被我忽略了。