Home >Backend Development >PHP Tutorial >php implements simple chat function

php implements simple chat function

Guanhui
GuanhuiOriginal
2020-05-06 13:50:564426browse

php implements simple chat function

php implements simple chat function

1. Create a chat message table. The fields in the table include message content, sending time and sender’s name. Name;

SQL:

CREATE TABLE `guanhui`.`message` ( 
    `id` INT(10) NOT NULL AUTO_INCREMENT COMMENT '消息ID' , 
    `content` VARCHAR(255) NOT NULL COMMENT '消息内容' , 
    `sender` VARCHAR(60) NOT NULL COMMENT '发送者' , 
    `send_time` INT(10) NOT NULL COMMENT '发送时间' ,
     PRIMARY KEY (`id`)
 ) ENGINE = MyISAM;

2. Create a php file to query the chat messages and output it in json format;

$con = mysql_connect("localhost","","");
if (!$con) {
    die('Could not connect: ' . mysql_error());
}
mysql_select_db("chat", $con);
mysql_query("set names 'utf8'");            
$sql = "SELECT * FROM  `message`";
$result = mysql_query($sql);
if(isset($result)){
    json_encode(array(
        'code' => 0,
        'msg' => 'OK',
        'data' => mysql_fetch_array($result, MYSQL_ASSOC)
    ))
} else {
    json_encode(array(
        'code' => 0,
        'msg' => '聊天信息为空!'
    ))
}

3. Use Ajax polling requests on the front end php file and display the message.

setInterval(function(){

    $.get('/get_message_list.php', function(data){

        $(data).each(function(value, item){
            $('#message_list').append('来自:' + data.sender + '的消息:' + data.message + '发送时间:', data.send_time);
        });

    });

}, 600);

4. Create send_message.php to receive the sent message and store the data in the database.

$send_time = date('Y-m-d H:i:s',time());;
$send = $_POST['sender'];
$content = $_POST['content'];
$con = mysql_connect("localhost","","");
if (!$con) {
  die('Could not connect: ' . mysql_error());
}
mysql_select_db("ing", $con);
mysql_query("set names 'utf8'");
$insert="INSERT INTO  `chat` (`id` ,`sender` ,`content` ,`send_time`) VALUES (NULL ,  '$sender',  '$content',  '$send_time')";
$result = mysql_query($insert);

5. Get the message to be sent on the front end and request send_message.php.

function sendcontent()
  {
    var xmlhttp;
    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
    }
    else
    {// code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function()
    {
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
      // 服务端返回了正确数据,开始响应处理
      {   
        document.getElementById("input").innerHTML="";
      } 
    }
    xmlhttp.open("POST","/send_message.php",true);
    var f=document.chat;
    var content = f.content.value;
    var sender = f.sender.value;
    //发送请求
    //这里使用Post方法传递参数;
    //将要构造的参数连接起来,接收的时候:$_POST['send'];
    var post_str= "content="+ content+"&sender="+sender;
    //使用post的时候必须在发送请求之前加上下面这句
    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    xmlhttp.send(post_str);
  }

The above is the detailed content of php implements simple chat function. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn