【问题标题】:How can I alert the user if a new line is inserted in the database如果在数据库中插入新行,如何提醒用户
【发布时间】:2014-02-26 23:31:54
【问题描述】:

我有一个桌面应用程序将值插入到带有字段 id、keyword 和 timestamp 的 mysql 表中

我有一个 php 页面,它在我的浏览器中保持打开状态,并列出了该数据库中的所有条目。

我想做的是让这个页面自动检查数据库中是否有新条目并警告我。此警告必须是声音。

如果一个条目的时间戳小于当前时间戳的 60 秒,我认为它是新条目。

所以,我有一个检查新条目的 mysql 查询,但我的主要问题是,如何在不手动刷新页面的情况下每 1 秒执行一次该查询?以及如何在发现新条目时发出声音警报?

提前致谢。

【问题讨论】:

    标签: javascript php mysql ajax xmlhttprequest


    【解决方案1】:

    尝试使用带有 setTimeout 的 ajax get 函数无限期运行:

    function checkDB()
    {
        $.get("checkDB.php","",function(data) {
            if(data=="1") //if new entry is present
            {
                //use sound manager to play a sound file
            }
        });
        setTimeout("checkDB()",1000); // this will ensure this function to run every 1000 milliseconds
    }
    

    sound manager link

    【讨论】:

    • 我得到“调用未定义函数 setTimeout()”。
    【解决方案2】:

    您可能想研究 WebSockets 或 Long Polling。 This 是一篇很好的帖子,详细介绍了您拥有的选项。 Here 是一个可能有助于长轮询的帖子。

    【讨论】:

      【解决方案3】:

      你可以使用 ajax 来实现这个和持久连接,因为它使连接保持打开状态

      【讨论】:

        【解决方案4】:

        这就是我设法做到的:


        在页面的<head> 节点内,代码如下:

        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
        
        <script type="text/javascript">// <![CDATA[
        $(document).ready(function() {
        $.ajaxSetup({ cache: false }); // This part addresses an IE bug. without it, IE will only load the first number and will never refresh
        setInterval(function() {
        $('#divToRefresh').load('dbcheck.php');
        }, 500); // refers to the time to refresh the div. it is in milliseconds.
        });
        // ]]></script>
        


        然后,在页面某处:

        <div id="divToRefresh">Running...</div>
        


        当然,我创建了一个名为 dbcheck.php 的新 php 文件,其中包含连接到数据库并包含以下内容:

        $sql3 = "SELECT keyword, timestamp FROM keywords ORDER BY id DESC LIMIT 1;";
        $query3 = $pdo->prepare($sql3);
        $query3->execute();
        $result3 = $query3->fetch();
        
        $timestampCheck = time() - 120;
        if ($result3['timestamp'] >= $timestampCheck)
        {
        echo "<div>NEW KEYWORD FOUND!</div>\n\n";
        echo "<div>", $result3['keyword'], "</div>";
        
        echo "<audio autoplay=\"autoplay\">
        <source src=\"alarm.wav\" type=\"audio/wav\">
        Your browser does not support the audio element.
        </audio>";
        
        }
        else
        {
        echo "Listening...";
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-02-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-06-17
          • 2015-09-30
          • 2018-10-28
          • 2019-05-08
          相关资源
          最近更新 更多