我正在尝试构建一个多用户聊天系统,其中数据保存在数据库中并根据请求提取。下面的代码只是一个例子,我知道它有很多很好的SQL注入,一旦整个工作正常,我会改变它。另外将php服务器代码保存在同一个文件中只是为了让代码整齐地放在一个地方,我在这里解释的问题仍然存在,当服务器代码在不同的php文件中时。
代码运行良好但问题是我的数据库在一段时间后停止响应一段时间。如果有更多用户同时聊天(此脚本的多个实例)正在进行,那么数据库很快就会停止响应一段时间,并且会在一段时间后开始响应。 请建议我哪里出错了。
<?php
if($_POST){
$db=mysqli_connect("localhost","***","****","****");
if ( isset($_POST['update']) ){
$q = 0;
$lasttime = isset($_POST['timestamp']) ? $_POST['timestamp'] : 0;
while (1){
sleep(3);
$mresult = mysqli_query($db,"SELECT * FROM tblchat WHERE msg_datetime > $lasttime");
$wresult = mysqli_query($db,"SELECT writer_alias FROM tblwriter WHERE writer_isactive=1 AND (UNIX_TIMESTAMP(NOW())-last_activity)<10");
if (mysqli_num_rows($mresult)){ $msgs = array(); while ($row = mysqli_fetch_object( $mresult )) { $msgs[] = $row; } mysqli_free_result($mresult); echo json_encode(array("writers"=>$writers,"msgs"=>$msgs)); flush(); break; }
if (mysqli_num_rows($wresult)){ $writers = array(); while ($row = mysqli_fetch_object( $wresult )) { $writers[] = $row; } mysqli_free_result($wresult); echo json_encode(array("writers"=>$writers,"msgs"=>$msgs)); flush(); break; }
++$q;
if ($q>15){ break; }
}
}elseif ( isset($_POST['save']) ){
$msg = isset($_POST['msg']) ? $_POST['msg'] : '';
if ($msg != ''){
$from = $_POST["from"];
$to = $_POST["to"];
mysqli_query($db,"INSERT INTO tblchat VALUES('".$to."','".$from."','".$msg."','".time()."')");
echo json_encode(array("success"=>"1"));
flush();
}
}
mysqli_close($db);
exit();
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>testing comet</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<body>
<p>
<input type="text" name="word" id="word" value="" />
<input type="button" name="send" value="Send" id="mybutton"/>
</p>
<div id="content"></div>
<script type="text/javascript">
var lastime = 0;
$("#mybutton").click(function(){
$.post(location.href, {save:"1",from:"1",to:"5",msg:$("#word").val()}, function(data){
console.log(data);
$("#word").val("");
}, "json");
});
$(document).ready( function(){ update(); } );
function update(){
console.log("update called");
$.ajax({ type: "POST", url: location.href, data: {update:"1",timestamp:lastime}, success: function(data1){
console.log(data1);
lastime = handleDATA(data1.msgs);
}, dataType: "json", complete: update, timeout: 60000 });
}
function handleDATA (data){
for(i=0;i<data.length;i++){
$("#content").append(data[i].msg_from +": "+ data[i].msg+"</br>");
}
return data[data.length-1].msg_datetime;
}
</script>
</body>
</html>
答案 0 :(得分:0)
虽然这可能是也可能不是绝对的解决方案,但让我们用你的代码解决一些问题(以及一些格式以帮助更好地说明):
旧部分(第7-15行):
while (1){
sleep(3);
$mresult = mysqli_query($db,"SELECT * FROM tblchat WHERE msg_datetime > $lasttime");
$wresult = mysqli_query($db,"SELECT writer_alias FROM tblwriter WHERE writer_isactive=1 AND (UNIX_TIMESTAMP(NOW())-last_activity)<10");
if (mysqli_num_rows($mresult)){ $msgs = array(); while ($row = mysqli_fetch_object( $mresult )) { $msgs[] = $row; } mysqli_free_result($mresult); echo json_encode(array("writers"=>$writers,"msgs"=>$msgs)); flush(); break; }
if (mysqli_num_rows($wresult)){ $writers = array(); while ($row = mysqli_fetch_object( $wresult )) { $writers[] = $row; } mysqli_free_result($wresult); echo json_encode(array("writers"=>$writers,"msgs"=>$msgs)); flush(); break; }
++$q;
if ($q>15){ break; }
}
顶部的新功能:
// This is separate of the while below, put this
// function at top of your script (less code later)
function toArray( myqli_result $result )
{
while( $row = mysqli_fetch_object( $result ) )
{
$array[] = $row;
}
mysqli_free_result( $result );
return $array;
}
New While Statement:
//Replacement While Function
while( $q < 15 )
{
sleep(3);
$mresult = mysqli_query( $db, "SELECT * FROM tblchat WHERE msg_datetime > $lasttime" );
$wresult = mysqli_query( $db, "SELECT writer_alias FROM tblwriter WHERE writer_isactive = 1 AND ( UNIX_TIMESTAMP( NOW() ) - last_activity ) < 10" );
//If you need both results, you must check for both results
//And do what you need to do, BEFORE break;
if ( mysqli_num_rows( $mresult ) > 0 && mysqli_num_rows( $wresult ) > 0 )
{
$msgs = toArray( $mresult );
$writers = toArray( $wresult );
echo json_encode( array( "writers" => $writers, "msgs" => $msgs ) );
flush();
break;
}
++$q;
}
干净的代码使程序员感到高兴,并且以后也可以更容易地进行调试。
如果您需要两个结果集(就像您所做的那样),您将不会像现在的代码那样获得这两个结果集,当您获得第一个结果集时,您将会突破它。这将允许在json_encode之前处理两个查询。
这里,toArray( mysqli_result $result )
是一个只接受mysqli_result
对象生成并返回数组的函数,同时释放结果。
如果您发现自己使用不同的变量多次编写相同的代码行,则可能需要为其创建一个函数。