1

My PHP/HTML code below displays data from a database on a website, refreshing it every few seconds in order to have the most up-to-date information. Is it possible to kill the database connection five minutes after the link to this website was clicked? The fields for the database connection are left blank for my own privacy. Could somebody show in my code how I would include this? Thanks

<HTML>            
    <head>                                                                                                                                                  
        <meta http-equiv="refresh" content="2">                                                                                                             
    </head>                                                                                                                                                 
</html>                                                                                                                                                     
<?php                                                                                                                                                   
    $db = mysqli_connect('', '', '', '') or die('Error connecting to MySQL server.');       
?>                                                                                                                                                          

<?php                                                                                                                                                       
    $servername = "";                                                                                                                               
    $username = "";                                                                                                                         
    $password = "";                                                                                                                                 
    $database = "";                                                                                                                 
    if (mysqli_connect_errno()){                                                                                                                            
        echo "Failed to connect to MySQL: " . mysqli_connect_error();                                                                                       
    }                                                                                                                                                       

    $conn = new mysqli($servername, $username, $password, $database);                                                                                       

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

    if(mysqli_connect_errno()){                                                                                                                             
        echo "Failed to connect to MySQL: " . mysqli_connect_error();                                                                                       
    }                                                                                                                                                       

    $result = mysqli_query($db, "SELECT * FROM patients2");                                                                                                 

    echo "<table border = 5>";                                                                                                                              
        echo "<tr>";                                                                                                                                        
        echo "<th>ID</th>                                                   <th>Patient name</th>       
             <th>Doctor name</th>                                       
             <th>Check in date</th>
             <th>Room number</th>
             <th>Bed number</th>
             <th>Notes</th>
             <th>Time</th>";
    echo "</tr>";


    while($row = mysqli_fetch_array($result)){                                                                                                              
        echo "<tr>";
            echo "<td>" . $row['id'] . "</td>";
            echo "<td>" . $row['patient_name'] . "</td>";
            echo "<td>" . $row['doctor_name'] . "</td>";
            echo "<td>" . $row['check_in_date'] . "</td>";
            echo "<td>" . $row['room_number'] . "</td>";
            echo "<td>" . $row['bed_number'] . "</td>";
            echo "<td>" . $row['notes'] . "</td>";
            echo "<td>" . $row['time'] . "</td>";
        echo "</tr>";
    }
    echo "</table>";
    mysqli_close($db);                                                                                                                                      
?>
MonBoy175
  • 75
  • 8
  • `` is this your way of keeping the most current content? Why not look into AJAX or websockets instead? And why are there two connections to the database? – Qirel Apr 05 '17 at 13:58
  • It just refreshes the page every 2 seconds, it's only a college project so this is easier – MonBoy175 Apr 05 '17 at 13:59
  • I'd use AJAX, a hacky approach could be setting a cookie and incrementing it on every refresh, at `60` don't display the ``. – chris85 Apr 05 '17 at 13:59
  • If its for a schoolproject, then websockets is most likely not easy to implement. I'd still look into using AJAX instead. Its a more maintainable and dynamic solution. – Qirel Apr 05 '17 at 14:00
  • I'm not looking to change the refresh function though, what I want is for the it to cut the database connection after being connected to it for two minutes, until the user runs the PHP file again when it would open the connection again – MonBoy175 Apr 05 '17 at 14:02
  • @MonBoy175 Because of the `refresh` and `user runs again` the page is load again (server does not know: by click or refresh!) and a new connection is made (evertime, so each 2 seconds). There is no long open database connection. – JustOnUnderMillions Apr 05 '17 at 14:04
  • 3
    The connection is closed, `mysqli_close($db)` when the page loads. The refresh is making a new connection every two seconds though. – chris85 Apr 05 '17 at 14:06
  • Oh okay so is it possible to do both? Refresh the page and disconnect from the server at different times? – MonBoy175 Apr 05 '17 at 14:07
  • @chris85 even without mysqli_close($db); it gets closed – Nomistake Apr 05 '17 at 14:26
  • The link to the server will be closed as soon as the execution of the script ends, unless it's closed earlier by explicitly calling mysql_close(). – Nomistake Apr 05 '17 at 14:27
  • 1
    @Nomistake Yes, but with the direct call you know it is closed at that point. `So, while explicitly closing open connections and freeing result sets is optional, doing so is recommended. This will immediately return resources to PHP and MySQL, which can improve performance.` -http://php.net/manual/en/mysqli.close.php – chris85 Apr 05 '17 at 14:28
  • @chris85 http://stackoverflow.com/questions/880885/is-closing-the-mysql-connection-important so i thing this is as good as closing it manually not? – Nomistake Apr 05 '17 at 14:31
  • So could someone show me how exactly I would cut the PHP connection after 2 minutes of it being open? – MonBoy175 Apr 05 '17 at 14:31
  • @MonBoy175 Why would you want that? – Nomistake Apr 05 '17 at 14:32
  • @MonBoy175 It is never open for 2 minutes. You could stop refreshing after 60 page loads. – chris85 Apr 05 '17 at 14:32
  • Okay so how would I stop refreshing automatically after 60 page loads? – MonBoy175 Apr 05 '17 at 14:32
  • See my first comment. `setting a cookie and incrementing it on every refresh` – chris85 Apr 05 '17 at 14:33
  • @Nomistake it's just for a college project, it needs to stop displaying data after a certain length of time – MonBoy175 Apr 05 '17 at 14:34

2 Answers2

0

You can use AJAX to dynamically refresh the content ever 2 seconds, by running an AJAX call at a specific interval. This means that the page itself isn't reloaded, but you run the query how ever often you need it. This means splitting up your code into two files.

First, the main file.

<?php 
$conn = new mysqli($servername, $username, $password, $database);                                                                                       

if ($conn->connect_error) {                                                                                                                             
    die("Connection failed: " . $conn->connect_error);                                                                                                  
}  
?>
<html>
    <head>
        <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script> <!-- Get latest jQuery libary -->
        <script>
            var refresh_timer = 2; // Seconds
            var stop_timer = 60; // Number of iterations to complete
            var count = 0;

            $().ready(function() {
                setInterval(function() {
                    if (count < stop_timer)  {
                        $.ajax({
                            url: "load_newest.php",
                            success: function(data){
                                count++;
                                $("#table_body").html(data);
                            }
                        });
                    }
                }, refresh_timer*1000);
            });
        </script>
    </head>
    <body>
        <table border=5>
            <thead>
                <tr>                                                                                                                      
                    <th>ID</th>                                                   
                    <th>Patient name</th> 
                    <th>Doctor name</th>
                    <th>Check in date</th>
                    <th>Room number</th>
                    <th>Bed number</th>
                    <th>Notes</th>
                    <th>Time</th>
                </tr>
            </thead>
            <tbody id="table_body">
                <?php 
                $result = $conn->query("SELECT * FROM patients2");    
                while($row = $result->fetch_assoc()){                                                                                                              
                    echo "<tr>";
                        echo "<td>" . $row['id'] . "</td>";
                        echo "<td>" . $row['patient_name'] . "</td>";
                        echo "<td>" . $row['doctor_name'] . "</td>";
                        echo "<td>" . $row['check_in_date'] . "</td>";
                        echo "<td>" . $row['room_number'] . "</td>";
                        echo "<td>" . $row['bed_number'] . "</td>";
                        echo "<td>" . $row['notes'] . "</td>";
                        echo "<td>" . $row['time'] . "</td>";
                    echo "</tr>";
                } ?>
            </tbody>
        </table>
    </body>
</html>

And the target file of AJAX, in this example, that's called load_newest.php and is in the same file folder as your main file.

<?php 
$conn = new mysqli($servername, $username, $password, $database);                                                                                       

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

$result = $conn->query("SELECT * FROM patients2");    
while($row = $result->fetch_assoc()){                                                                                                              
    echo "<tr>";
        echo "<td>" . $row['id'] . "</td>";
        echo "<td>" . $row['patient_name'] . "</td>";
        echo "<td>" . $row['doctor_name'] . "</td>";
        echo "<td>" . $row['check_in_date'] . "</td>";
        echo "<td>" . $row['room_number'] . "</td>";
        echo "<td>" . $row['bed_number'] . "</td>";
        echo "<td>" . $row['notes'] . "</td>";
        echo "<td>" . $row['time'] . "</td>";
    echo "</tr>";
} 

This will replace the body of the table every refresh_timer = 2; seconds with the latest query, and stop after executing it 60 times (which is 2 minutes, since you execute it every 2 seconds).

Qirel
  • 25,449
  • 7
  • 45
  • 62
  • Okay I'm gonna try this now and get back to you – MonBoy175 Apr 05 '17 at 14:38
  • Please do :-) This is untested, so if you encounter any errors, check your PHP logs, and the console in the browser for jQuery errors and report those back if you have any issues. – Qirel Apr 05 '17 at 14:40
  • Just ran it there and a fatal error occured at line 45: 'Uncaught Error: Call to a member function query() on null' which is line '$result = $conn->query($db, "SELECT * FROM patients2");' – MonBoy175 Apr 05 '17 at 14:48
  • Which means that the connection object in *your actual code* isn't named `$conn`, but something else. Uh, hold on, that's a syntax error too - there should only be 1 argument, the querystring. Let me update the answer. Slight copy/pasta error ;-) – Qirel Apr 05 '17 at 14:50
  • In my actual code, Conn is a file to connect to the database – MonBoy175 Apr 05 '17 at 14:53
  • A *file* you say? Please try to read and understand the snippet I posted, not just copy/paste it. `$conn = new mysqli` creates the connection object into a variable called `$conn`, which is then used to perform queries on (`$conn->query(..);`). Also, if it's named `$Conn`, that's not the same as `$conn` (case sensitive). – Qirel Apr 05 '17 at 14:55
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/139988/discussion-between-monboy175-and-qirel). – MonBoy175 Apr 05 '17 at 15:01
-1

According to this awnser https://stackoverflow.com/a/12434864/6745860

Maybe you can do your msqli_close like this:

    Your PHP code called by the job will simply do (in pseudo code):

$batchRecords = takeAbunchOfRecordsWhereStatus(NOT_SENT);
while($batchRecords) {
    if($creationDate + 10 minutes >= now()) {
        sendEmail();
        markRecordAsSent();
    }
}
Community
  • 1
  • 1
Pablo Mariante
  • 350
  • 3
  • 11