php – 在数据库中插入新数据时警告用户

我不知道如何搜索这个,所以我有点迷失(我在这里看到的两个主题已经关闭).

我有一个新闻网站,我想在数据库中插入新数据时警告用户.我想在StackOverflow上这样做,我们会在没有重新加载页面的情况下收到警告,或者在facebook中警告你没有重新加载的新消息/通知.

哪种方法最好?它是某种具有超时的监听器,不断检查数据库吗?听起来效率不高……

提前致谢.

解决方法:

你需要javascript ajax和json以及回调函数来不断检查.它可以通过推送服务完成,但PHP很糟糕,你需要websockest等.facebook使用超时调用.不确定stackoverflow

   refreshInterval = 500
  refreshTimeout = setTimeout( getNotificationCounts, refreshInterval );
function getNotifications() {
        $.ajax({
            url : 'path_to_your_PHP',
            type : 'POST',
                    data:   //put for exampel user_id but it cvan be handled by sesion as well
            dataType : 'json',
            success : function(data) {
                alert('You have'+ data.total +' new messages')
                refreshTimeout = setTimeout( getNotificationCounts, refreshInterval ); //this will check every half of second
            }
        });
    }

然后在PHP中,例如,您在数据库中有一个标志,您可以使用该标志检查数据是否是新数据库.注意格式化和正确的sql转义

    $result=MysqL_query("SELECT count(*) as total from myTable where user_id=$_POST['user_id'] AND is_read=0"); 

      //note instad of $_POST you can use session if users are logged in, or however you are handling it
        $data=MysqL_fetch_assoc($result);
        echo json_encode($data)

;

之后,您可以创建另一个ajax调用,在用户单击它们时将其标记为已读.或打开对话框列表或wahtever

MysqL_query("UPDATE myTable WHERE user_id=$_POST['user_id'] SET  is_read=1");

相关文章

IE6是一个非常老旧的网页浏览器,虽然现在很少人再使用它,但...
PHP中的count()函数是用来计算数组或容器中元素的个数。这个...
使用 AJAX(Asynchronous JavaScript and XML)技术可以在不...
Ajax(Asynchronous JavaScript and XML)是一种用于改进网页...
本文将介绍如何通过AJAX下载Excel文件流。通过AJAX,我们可以...
Ajax是一种用于客户端和服务器之间的异步通信技术。通过Ajax...