1

I have a (python) program running that is constantly sending data to a MySQL database, and I use html/php to graph these data. A simple x/y data point graph where x = number of measurement (1, 2, 3...) and y = value of the measurement taken (323, 4938, 2...).

I use a 2 column table, which will add a new row every time a new measurement is taken. I use python/selenium in order to update the page every time a new input is made

//python
driver = webdriver.Chrome(chrome_options=option, executable_path=PATH)
driver.refresh()

I want to add a "RESET" button the page, which will delete the data inside the table. This is the way I am currently trying to achieve this:

<?php
 if($_SERVER['REQUEST_METHOD'] == 'POST'){
   $handle = $dbconnection->prepare('TRUNCATE TABLE measurements'); //deletes all the data for my x, y graph.
   $handle -> execute();
?>

<form action="" method="post">
 <input type ="submit" name ='reset' value='RESET' />
 <br/>
</form>

This partially works, since it does send the query and deletes the data from my table if I press the button. The problem is that it deletes the table every time the webpage refreshes once I press the button. What I wish would happen is that the table only gets deleted when I press the button, not everytime the webpage refreshes.

How can I change the HTML/PHP code in order for the button to send the query only once it is pressed, and not every time once it is pressed?

CKiamy
  • 51
  • 3
  • 1. Redirect to the page after the query is finished. 2- use the PUT methods to create a new resource and DELETE method to remove a resource. – Mehrwarz Apr 18 '22 at 06:11
  • 1
    The convention to avoid this kind of problem is called PRG - Post, Redirect, Get. POST to your PHP to make chages, when the update is done the PHP should issue a redirect, even if it just to the same page, which will be retrieved with a GET. Reloading the last request - a GET - does not resubmit your POST. – Don't Panic Apr 18 '22 at 07:23

1 Answers1

1

As an alternative to "post/redirect/get" pattern covered in comments:

session_start(); // Start new or resume existing session
$_SESSION['exec_reset'] = 1;
if($_SERVER['REQUEST_METHOD'] == 'POST' && $_SESSION['exec_reset'] === 1){
    $handle = $dbconnection->prepare('TRUNCATE TABLE measurements'); //deletes all the data for my x, y graph.
    $handle -> execute();
    $_SESSION['exec_reset'] = 0; // prevents execution on a refresh
}
Ersin
  • 124
  • 3