php realizes simple chat function

1. To create a chat message table, its fields include message content, sending time and sender's name;

SQL:

CREATE TABLE `guanhui`.`message` ( 
    `id` INT(10) NOT NULL AUTO_INCREMENT COMMENT 'news ID' , 
    `content` VARCHAR(255) NOT NULL COMMENT 'Message content' , 
    `sender` VARCHAR(60) NOT NULL COMMENT 'sender ' , 
    `send_time` INT(10) NOT NULL COMMENT 'Send time' ,
     PRIMARY KEY (`id`)
 ) ENGINE = MyISAM;

2. Create php file to query the chat message 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' => 'Chat message is empty!'
    ))
}

3. At the front end, Ajax is used to poll the request php file and display the message.

setInterval(function(){
 
    $.get('/get_message_list.php', function(data){
 
        $(data).each(function(value, item){
            $('#Message [u list '). Append ('message from' + data.sender + ':' + data.message + 'sending time:', 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 send at 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)
      // The server returns the correct data and begins to respond
      {   
        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;
    //Send request
    //Here, the Post method is used to pass parameters;
    //Connect the parameters to be constructed, when receiving: $_POST['send '];
    var post_str= "content="+ content+"&sender="+sender;
    //When using post, you must add the following sentence before sending the request
    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    xmlhttp.send(post_str);
  }

For more information, please visit:

Tencent T3-T4 standard boutique PHP architect tutorial directory, as long as you read it to ensure a higher salary (continuous update)

Tags: PHP SQL JSON Database

Posted on Thu, 07 May 2020 08:33:20 -0700 by thatsme