Wednesday, 10 May 2017

How to loop through messages from mysql database and display them correctly

I'm building a chat program.

Every time a user sends a message it gets stored in a table called 'messages'.

When a user disconnects, and later connects again, the old messages should be displayed the same way, as when they were send. In the image you can see that received messages are grey, and others are blue: enter image description here

When a user connects, I am retrieving the old messages with this code:

// Retrieve conversation
        client.on("retrieveConversation", function(data){
                var peopleName = data.result.conversation_receiver;
                var retrievedMessages = [];
                connection.query("SELECT * FROM `messages` WHERE `message_key` = '" + data.result.conversation_key + "'", function(error, results, fields){
                        if (error) {
            console.log(error);
            return;
                } 
                else if (results) {
                        console.log("Messages: ", results);
                } 
                });
                console.log("Retrieving conversation", peopleName);
                client.emit("addConversationForSelf", peopleName);
        });

And the result looks like this in the console: enter image description here

How can I loop through the results and control which messages (from body) should emit to either: 1.client.emit("newMessageToOthers", message); or 2. client.emit("ownMessage", message); - Note that these two options control whether the messages are grey or blue.



via JonasSH

No comments:

Post a Comment