php+comet反向Ajax聊天小案例

首先建表
create table comet_msg(
    id int unsigned not null auto_increment primary key,
    content varchar(200) not null default '',
    flag tinyint unsigned not null default 0
)engine=innodb default charset=utf8;

<?php
    set_time_limit(0);
    // ob_start();// 測試時,若是開啓ob_start反而沒有效果
    $pad = str_repeat('*',6000);
    echo $pad;
    echo '<br />';
    // ob_flush();
    // flush();
    $conn = mysql_connect('localhost','root','2012o912@');
    // mysql_select_db('test',$conn);
    mysql_query("use test");
    mysql_query("set names 'utf8'");

    while(1){
        $res = mysql_query("select * from comet_msg where flag=0 order by id desc",$conn);
        $row = mysql_fetch_assoc($res);
        
        if(!empty($row)){
            echo $row['id'].':'.$row['content'];
            echo '<br />';
            mysql_query("update comet_msg set flag=1 where id='".$row['id']."'");
        }
        ob_flush();
        flush();
        sleep(1);
    }
?>
在瀏覽器中打開頁面,而後在MySQL中插入語句 insert into comet_msg (content) values ('abc1'); insert into comet_msg (content) values ('abc2'); insert into comet_msg (content) values ('abc3'); insert into comet_msg (content) values ('abc4'); insert into comet_msg (content) values ('abc5'); insert into comet_msg (content) values ('abc6'); 沒插入一次數據都會在瀏覽器中顯示出來 以上源自於燕十八反向Ajax,特別感謝18哥的精彩講解
相關文章
相關標籤/搜索