1

调用一个函数,如:-

$setmessage = setlatestmessage($sessionid, $sendersuserid, $message1);

该函数在文件functions.php中,我已将其包含在此文件中该函数是:-

function setlatestmessage($sessionid, $userid, $message, $status = 0) {
    $dbc = mysqli_connect(hostname, username, password, database)
            or die("Error connecting database");

    // there was no row, so just add a row
    $query2 = "insert into table(session_id, user_id, message, status) values ( $sessionid, $userid, '$message', $status)";
    mysqli_query($dbc, $query2);

    // if a row was affected, close connection and send true
    if (mysqli_affected_rows($dbc) == 1) {
        mysqli_close($dbc);
        return TRUE;
    }
    mysqli_close($dbc);
    return FALSE;
}

现在,就在我调用这个函数之后,脚本就像

if (!$setmessage) {
                echo '<status>0</status>';
            } else {
                // fetch id of the row just inserted
                $query2 = "select id from game_messages where session_id = $sessionid and message = '$message1' and user_id = $sendersuserid order by datetime desc limit 1";
                $result2 = mysqli_query($dbc, $query2);

                if (mysqli_num_rows($result2) == 0) {
                    // if no row was returned
                    // case never should happen
                    echo '<status>10</status>';
                }
                else{echo'done';}

我得到的输出是10。

但是,如果我只是在函数调用下放置一个 sleep(50),或者我只是编写函数正在执行的操作,而不是函数调用,我会得到正确的输出。无法弄清楚为什么会这样。

4

1 回答 1

0

setlatestmessage()如果您在函数 usingmysqli_insert_id()或错误时返回最后一个插入查询生成的 ID,将会更容易和更简单。然后,您只需检查:

$messageID = setlatestmessage($sessionid, $sendersuserid, $message1);

if ($messageID !== false)
{
    echo '<status>0</status>';
}
else
{
    echo '<status>10</status>';
}
于 2012-06-22T08:37:44.143 回答