普通网友 2012-12-02 10:39
浏览 56
已采纳

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

I don't know how to search about this so I'm kinda lost (the two topics I saw here were closed).

I have a news website and I want to warn the user when a new data is inserted on the database. I want to do that like here on StackOverflow where we are warned without reloading the page or like in facebook where you are warned about new messages/notifications without reloading.

Which is the best way to do that? Is it some kind of listener with a timeout that is constantly checking the database? It doesn't sounds efficient...

Thanks in advance.

  • 写回答

1条回答 默认 最新

  • douna1941 2012-12-02 11:02
    关注

    You need javascript ajax and json and callback function to check constantly. It can be done by push services but PHP is bad with that and you need websockest, etc. facebook uses timeout calls. not sure for the 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
                }
            });
        }
    

    then in PHP, for example you have a flag in database with which you check if data is new to teh databse. Mind the formatting and to proper sql escape

        $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)
    

    ;

    After that you can create another ajax call that marks messages as read once user clicks on them. or opens a dialog listing or wahtever

    mysql_query("UPDATE myTable WHERE user_id=$_POST['user_id'] SET  is_read=1");
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号