我正在开发一个 CMS,以允许用户访问 MySQL 数据库中的记录并对其进行分类。我已经为此 CMS 创建了一个用户登录系统。我正在尝试编写一个锁定功能,该功能将监视何时查看记录,以便其他用户无法访问该记录。这是为了防止多个用户尝试同时写入同一条记录。
到目前为止,这部分工作得相当好。当他们访问该记录时,我会更新该特定记录的 MySQL 数据库中的“in_use”字段,以显示该记录正在被查看。当他们提交带有记录分类的表单时,我更新字段“in_use”以表明它不再被查看。
我遇到的问题是当用户关闭浏览器而不提交表单时,或者当他们离开页面时。
我一直在尝试使用 AJAX 对 beforeunload 事件运行更新,但没有成功。
***** readRecord.php*****
<h1>Analyze</h1>
//PHP include that contains functions for php queries to the MySQL database.
<?php
include 'core/database/record_functions.php';
?>
//Form to search MySQL database by Case Number and Button to manually release a record that is in_use.
<form action="" method="post">
<p id="case_search">Search records by Case Number: <input type="text" id="case_num_field" name="case_num">
<input type="text" name="in_use" id="in_use" readonly="readonly" hidden="hidden" value="1">
<input type="text" name="user" id="user" readonly="readonly" hidden="hidden" value="<?php echo $_SESSION['username']; ?>">
<input type="submit" name="Submit" value="Select" id="case_num_submit">
<input type="Submit" name="release record" value="Release the current record" onclick="<?php update_in_use($_SESSION['case_num'], 0); ?>">
</p>
</form>
//Includes for jQuery library and AJAX code for automatically releasing the record on page navigation or close.
<script type="text/javascript" src="core/jquery-2.1.3.js"></script>
<script type="text/javascript" src="ajaxBridge.js"></script>
... code continues for reading records
... when the form is submitted update_in_use is called again to set the value to 0
***** ajaxBridge.js *****
// This code is supposed to run the query on releaseVariable.php to update the in_use field to 0 on the beforeunload event.
window.addEventListener("beforeunload", function(event){
if(xmlHttp.readyState==4)
{
xmlHttp.open("POST", "releaseVariable.php", true);
xmlHttp.send();
event.returnValue = "Hey it worked!";
}
event.returnValue = "Hey it failed!";
});
*****releaseVariable.php *****
// This simply runs the update_in_use function to set the in_use field to 0 for this particular case.
<?php
include 'core/init.php';
include 'read_record.php';
protect_page();
update_in_use($_SESSION['case_num'], 0);
?>
我的处理方式正确吗?如果不是,我该如何解决这个问题?
如果这是一个好方法,那么我的代码在哪里误入歧途了?
最佳答案
我决定放弃这种方法并改用 php SESSION 变量。
关于javascript - 卸载前更新 MySQL 字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28617996/