php - Code runs when refresh

787

Why is this code running when I refresh page? Is somethink wrong with condition isset($_POST['topuj'])? "Topuj" is name of button.

<?php
if(isset($_COOKIE['prihlaseny'])) {
require('db.php');
$meno1 = $_COOKIE['prihlaseny'];

$prikaz = $mysql->query("SELECT * FROM `uzivatelia` WHERE `meno`='{$meno1}'");
while($a = $prikaz->fetch_assoc()) {
$kredit = $a[kredity_topovania];
$plus = $a[topovanie];

if( $kredit > 0) {
echo "
<form method='post'>";
if( $kredit == 1) echo "Máš $kredit kredit."; 
if( $kredit == 2 || $kredit == 3 || $kredit == 4) echo "Máš $kredit kredity."; 
if( $kredit > 4) echo "Máš $kredit kreditov."; 
echo "<br /><button name='topuj' value='$a[id]' />Topovať</button>
</form>
";}

}
if( isset($_POST['topuj'])) {
$id = $_POST['topuj'];
$mysql->query("UPDATE `uzivatelia` SET topovanie='$plus'+1, kredity_topovania='$kredit'-1 WHERE id='{$id}'");
}
848

Answer

Solution:

You are most likely experiencing the "double submit problem"

If the last HTTP request made by a browser was a POST request with data payload (in your case inputs from a form) and you refresh/reload the webpage the browser will re-submit the POST data.
Which will obviously trigger yourisset($_POST['topuj']) condition.

The browser will generally issue a warning that it is going to do this.

If you are developing and you want to avoid this, I would browse back to the form by re-typing the URL in the address bar or clicking a link back to the form.

For a production app you may want to implement a better solution to prevent the user being able to reload the page.
For example redirect the user away from the page after a successful submission, but there are many (possibly better) solutions as well.

People are also looking for solutions to the problem: php - htaccess need name in front of domain

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.