Skip to content
Advertisement

Fetch data from database with PHP every 5 seconds

I have an index.php and a data.php file. I use the data.php to fetch data from my database (which stores the messages), and the index.php to map the fetched data into the div .messages_container.

The code for index.php

<?php
    include("data.php");

?>

<html>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<head>
    <meta name="viewport">
    <title>title</title>
    <link rel="stylesheet" type="text/css" href="styles.css">
    <noscript>Enable Javascript to access the full functionality of the website.</noscript>
</head>
    <body>
    <div class="header"><h1 id="main_header_text">forum</h1></div>
    <div class="send_message">
        <form action="data.php" method="POST">
            <input type="text" name="usr" placeholder="name">
            <input type="text" name="msg" placeholder="message">
            <input type="submit" value="send">
            <span class="send_error_span"><?php echo $send_error; ?></span>
        </form>
    </div>
    <div class="messages_container">

            <?php
                foreach ($datas as $data) {
                    echo $data["id"] . " > <span class='username_in_display'>" . $data["sender"] . "</span>" . " " . "<span class='message_in_display'>" . $data["message"] . "</span>" . "<br>";
                }
                if(!$datas) {
                    echo "no messages yet.";
                }
            ?>
    </div>
    </body>

    <script>
        setInterval(
            function() {refresh();}, 1000
        );
        function refresh() {
            //something there maybe?
        }

    </script>

</html>

This is the data.php

<?php 
    include("config.php");

    $conn = new mysqli($servername, $username, $pass, $dbname);

    if($conn->connect_error){
        die("Connection failed: " . $conn->connect_error);
    }

    $sql = "select id, ifnull(sender, 'anonymous') as sender, message from messages;";
    $res = $conn->query($sql);

    $datas = array();

    if($res->num_rows > 0) {
        while($row = $res->fetch_assoc()) {
            $datas[] = $row;
        }
    }


    $send_error = "";

    if($_SERVER["REQUEST_METHOD"] == "POST") {
        if(!empty($_POST["msg"])) {
            $n = $conn->real_escape_string($_POST["usr"]);

            if($n == "") {
                $n = "anonymus";
            }

            $m = $conn->real_escape_string($_POST["msg"]);
            if($conn->query("insert into messages (sender, message) values ('$n', '$m');") === TRUE) {

            } else {
                echo "error: " . $conn->error;
            }


        } else {
            $send_error = "<br><br>empty message!";

        }

        unset($_POST);
        header("Location: index.php");
        exit;

    }

    $conn->close();
?>

It works fine, but it only refreshes once I send a message or refresh the page. I want it to refresh every 5 seconds, so I don’t need to manually refresh every time to see new messages. I also don’t want to refresh the entire page, just rerun the PHP script part which fetches the database data somehow.

I tried with AJAX but the problem is that it loads the entire page into the messages_container div once it calls data.php

Advertisement

Answer

You could use ajax to reload the data from the server side but that will over-load the client side and use too many resources on the client side.

The solution for this is to use sockets.

A socket is an abstraction through which an application may send and receive data,in much the same way as an open file allows an application to read and write data to stable storage. A socket allows an application to “plug in” to the network and communicate with other applications that are also plugged in to the same network. Information written to the socket by an application on one machine can be read by an application on a different machine, and vice versa.

You can read more about it here : https://socket.io/

This might help too : Websockets PHP / AJAX / Javascript refresh client

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement