For the following code I have a problem. When i fill in the form and submit it inserts a new database value. But when I refresh the page it does it again automatically with the same data, and keeps doing it whenever i refresh. How do i stop this?

<html>
<head>
<title>Using Default Checkbox Values</title>
</head>
<body>
<?php
// Include our login information
include('db_login.php');

$self = htmlentities($_SERVER['PHP_SELF']);
echo ('
<form method="POST" action="'.$self.'">
ID: <input type="text" name="id" /><br />
Name: <input type="text" name="name" /><br />
Comment: <input type="text" name="comment" /><br />
Date: <input type="text" name="date" /><br />
Other: <input type="text" name="other" /><br />
<input type="submit" value="Go!" /><br />
</form>
');

if(!$_POST['name'] == ''){
$query1 = "INSERT INTO `unknown`.`comments` (`id`, `user`, `comment`, `date`, `other`) VALUES (NULL, '$_POST[name]', '$_POST[comment]', '2010-10-23', '$_POST[other]')";
$result1 = mysql_query( $query1 );
$_POST['name'] = '';
unset($_POST);
}
// Assign the query
$query = "SELECT * FROM comments";
// Execute the query
$result = mysql_query( $query );
if (!$result){
die ("Could not query the database: <br />". mysql_error( ));
}
// Fetch and display the results
while ($result_row = mysql_fetch_row(($result))){
echo 'ID: '.$result_row[0] . '<br />';
echo 'Author: '.$result_row[1] . '<br /> ';
echo 'Comment: '.$result_row[2] . '<br /> ';
echo 'Date: '.$result_row[3] . '<br /> ';
echo 'Other: '.$result_row[4] . '<br /><br />';
}
//Close the connection
mysql_close($connection);
?>
</body>
</html>

Dani AI

Generated

You are seeing classic duplicate form submission: when the response to a POST is an HTML page, a browser refresh repeats the last request, so the INSERT runs again. Unsetting $_POST only clears PHP’s copy for that one request; the browser will still re-send the body on refresh. A session flag (as suggested) can help, but the robust fix is the Post/Redirect/Get (PRG) pattern. After a successful insert, redirect with a 303 status to the same URL so the next refresh is a harmless GET. ’s tip points in this direction; below is the complete flow with validation and a one-time token to block double-clicks/back-button resubmits. Unsetting a single $_POST field (as noted) is not sufficient by itself.

<?php
session_start();

// Generate a one-time token on GET
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    $_SESSION['form_token'] = bin2hex(random_bytes(16));
}

// Handle submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!hash_equals($_SESSION['form_token'] ?? '', $_POST['form_token'] ?? '')) {
        http_response_code(400);
        exit('Invalid or reused submission.');
    }
    unset($_SESSION['form_token']); // one use only

    // Use PDO (mysql_* is removed in modern PHP)
    $pdo = new PDO('mysql:host=localhost;dbname=unknown;charset=utf8mb4', 'user', 'pass', [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    ]);

    if (!empty($_POST['name'])) {
        $stmt = $pdo->prepare('INSERT INTO comments (user, comment, date, other) VALUES (?,?,CURDATE(),?)');
        $stmt->execute([$_POST['name'], $_POST['comment'] ?? '', $_POST['other'] ?? '']);
    }

    header('Location: ' . $_SERVER['REQUEST_URI'], true, 303);
    exit;
}
?>
<!-- In your form include: -->
<input type="hidden" name="form_token" value="<?php echo htmlspecialchars($_SESSION['form_token'] ?? '', ENT_QUOTES); ?>">

Notes:

  • Your original if(!$_POST['name'] == '') relies on tricky operator precedence; prefer if (!empty($_POST['name'])).
  • Consider a UNIQUE constraint or an idempotency key column if true duplicates must never be stored.
  • If you keep posting back to self, use action="" or safely escape $_SERVER['REQUEST_URI'] to avoid XSS, and always exit right after header(...).

Recommended Answers

All 3 Replies

Write something in a $_SESSION variable to detect that you already stored the form.

Or use the below code to send them to a new page that says whatever you want:

<?
header("Location: file.php");
?>

You must unset the $_POST somewhere in the end of the document (where you don't use it anymore):

<?php
unset($_POST['name'])
?>
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.