0
votes

I am trying to create a simple chat application. Below, you notice that my PHP code is inside a div, which is for the chat data, and that div is inside another div representing the chat box. Inside my PHP code, I wrote my PHP function. It connects to the myPHPadmin server and then it has a query to place the inputted data from the person's name into the database. I have an echo statement to write what the person wrote. As soon as I press the submit button, it will show what the person wrote, but if I type another message in, the message text gets replaced. How do I get my PHP code to dynamically create echo statements as if it were a chat conversation? It should create a new line each time I send a message.

<div id="chat_box">
    <div id="chat_data">
        <?php
             function sendMessage() 
             {
                //I hid my login credentials
                $servername = "";
                $username = "";
                $password = "";
                $dbname = "";

                // Create connection
                $dbc = new mysqli($servername, $username, $password, $dbname);


                // Check connection
                if ($dbc->connect_error)
                {
                    die("Connection failed: " . $dbc->connect_error);
                }



                $name = $_POST['name'];
                $msg = $_POST['log'];

                $query = "INSERT INTO `chatApp` (`name`, `pwd`, `message`) VALUES ('$name', NULL, '$msg')";
                $run = $dbc->query($query);



                echo "<p>" . $name . " : </p> ";
                echo "<p>" . $msg . "</p>";

              }

        ?> 

            </div>

          </div>
1
Your code is vulnerable to SQL injection and will be hacked even if you are escaping inputs! Use Prepared Statements instead. Check: How can I prevent SQL injection in PHP - Spoody
either you do it client side via javascript. Or you simply select and display the last messages (out of database) - Jeff
seperate the logic of saving the message and displaying the messages. - Jeff
also have a read about database normalization. (because now you save the user's name with the message) - Jeff

1 Answers

0
votes

Use Ajax (Asynchronous Javascript and XML) to fullfill your requirement. Since, PHP is a server side programming language, on clicking submit button the page need to contact with the server and should refresh for getting data.

Ajax will remove the headache of refreshing and get the data from the server on the way without refreshing your page. Learn the basics of Ajax and apply it in your project on your own.